I have been using external txt files to save the score and the player name (I only save one score and one name in two different files)
When there is a new highscore it saves over the old one. I had it all working perfectly until I published the project, now it cant locate the file.
I embedded the txt file but I cant write to it.
I am using the following code.
using (StreamWriter write = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "highscore.txt")) // read the high score text file
{
write.WriteLine(player.score); // saves the new high score
write.Close(); // closes the file
}
using (StreamWriter write = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "nickname.txt")) // reads the high score text file
{
write.WriteLine(player.nickname); // save new highscore name
write.Close(); // close file
}
When I run the games from a USB or a CD they wont read -
So my question is - how to I place the txt files into a directory my game can see/find?
When you are running your program from the CD, your application's path is on that CD, so the code:
AppDomain.CurrentDomain.BaseDirectory + "highscore.txt"
points to a readonly CD path.
in order to be able to save the file properly, you can:
ask user to enter a path to which he/she wants the data to be saved
use one of the available directories (look in the Environment class),
for instance using the:
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Please also note that it is better to use Path.Combine() to concat the paths rather than '+' sign.
Related
get current date and make directory and second when directory is created, in that directory I have to store excel file and also save file as current date.
String Todaysdate = DateTime.Now.ToString("dd-MM-yyyy");
if (!Directory.Exists("C:\\Users\\Krupal\\Desktop\\" + Todaysdate))
{
Directory.CreateDirectory("C:\\Users\\Krupal\\Desktop\\" + Todaysdate);
}
This code have made directory with current date.
But when I want to store file in that directory, it generates the error:
Could not find a part of the path
'D:\WORK\RNSB\RNSB\bin\Debug\22-01-2020\22-01-2020.XLS
Belove path is store excel file that i have to store.
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
Actually you are making the directory in a path then you are saving the .xls in another path.
You are making the directory using this path:
"C:\\Users\\Krupal\\Desktop\\" + Todaysdate
Then, here the path where you are trying to save the .xls:
Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"
The error shows the problem clearly, it could not fin this path:
D:\WORK\RNSB\RNSB\bin\Debug\22-01-2020\22-01-2020.XLS
While creating the .xls you are omitting the root path, so the process looks for the path 22-01-2020\22-01-2020.XLS in his working directory D:\WORK\RNSB\RNSB\bin\Debug.
You just need to align those paths: I sugget you to use relative paths, so here how you should fix your code:
String Todaysdate = DateTime.Now.ToString("dd-MM-yyyy");
if (!Directory.Exists(Todaysdate))
{
Directory.CreateDirectory(Todaysdate);
}
//then
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
I presume you are running your WinForms application in Debug mode. This means that your current path is [your application path]\bin\Debug. If you look in file explorer, you will find that an executable has been created there. When using StreamWriter without an absolute file name, the file it tries to create is relative to the current execution path (in your case 'D:\WORK\RNSB\RNSB\bin\Debug'). StreamWriter will create a new file, if one does not exist, but it will not create a new folder, and you are passing it Todaysdate + "\\" which is effectively a new folder. Hence you are getting the error message.
To fix your problem, you need to provide the absolute path to your newly created directory thus:
using (System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\Users\\Krupal\\Desktop\\" + Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
Winforms always expect directories inside Debug Folder, since it's EXE file is inside Debug and try to find it inside Debug folder.
In error it clearly shows that it is looking inside "Debug" folder.
Can you check whether File Exists in the mentioned folder created by you in C Drive.
// To Write File
System.IO.File.WriteAllLines(#"C:\Users\Public\TestFolder\WriteLines.txt", lines);
You can follow this MSDN Post, hope it helps, if Yes, please Upvote it
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file
I have a quiz that has a login feature but, when you change pc you must also change the drive the file is located e.g D drive, E drive etc...
Currently its set to F. Is there something i can add that will make it automatically search each drive for the file?
Here is my code
if (File.Exists(#"F:\C# Completed quiz\adam new\Mario quiz\bin/PlayerDetails.txt"))
{
string[] lines = File.ReadAllLines(#"F:\C# Completed quiz\adam new\Mario quiz\bin/PlayerDetails.txt");
I'd recommend you just put it in the AppData or MyDocuments folder:
string filename = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "C# Completed quiz","adam new","Mario quiz","bin","PlayerDetails.txt");
//or Environment.SpecialFolder.MyDocuments
if (File.Exists(filename))
{
string[] lines = File.ReadAllLines(filename);
}
you need to enumerate the hard drives on the system and inspect them one at a time
https://msdn.microsoft.com/en-us/library/system.io.directory.getlogicaldrives(v=vs.110).aspx
shows how to enumerate the hard drives on the system
This answer uses what looks like a better way
How can I determine if a given drive letter is a local/mapped/usb drive?
Once you know a drive is a mounted drive the you should look at <drive>:/<your path>
Use Resource file to store your txt inside the application or just distribute it with your executable. To add resource file:
Right click on your project and select Properties
Go to Resources tab and create new file
Click Add resource -> Add Existing File...
Choose your text file and click Open
The file can now be accessed like string:
var lines = Properties.Resources.PlayerDetails;
If the file is in the same folder as your exe then you can access it in this way:
var lines = File.ReadAllLines("PlayerDetails.txt");
Edit: Note the comment below if you prefer to use this method.
I'm using C# windows application .
I want to save files in my local system.
I used Open File dialog to attach the files.
Here the text inside the file is copying,I want the file itself to get copied with a new name.But what I am really looking for is , it should just save the file automatically and not show the SaveDialog Box?
How it can be done in windows application.Can anybody help me please?
The code is shown below:
private string GetFileName()
{
OpenFileDialog op1 = new OpenFileDialog();
DialogResult result = op1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
txtEn.Text = op1.FileName;
FileName = op1.FileName;
//MessageBox.Show(FileName);
File.Copy(op1.FileName, #"D:\Backup\");
}
return FileName;
}
SQL Server 2012 seems unrelated to your question. Provided that you have proper access rights to the target directory, then in order to automate the procedure (as per your question) you don't need to use the OpenFileDialog; just a single line should suffice the goal:
//Overwriting a file of the same name is not allowed
File.Copy(FileName, #"D:\Backup\" + FileName)
or
//Overwriting a file of the same name is allowed
File.Copy(FileName, #"D:\Backup\" + FileName, true)
You can also apply some additional logic pertinent to backup file naming (upon necessity).
Hope this may help. Best regards,
Are you trying to copy a file from some x location on your file system to y location (in your case D:\Backup folder) in the file system? If that is the requirement here, I see that you are using the FileName property of OpenFileDialog which gets the File path. This you are appending to D:\Backup. You should instead use the Path.GetFileName property to first extract the file name with extension and then append it to the new folder path
File.Copy(fileName, #"D:\Backup\" + Path.GetFileName(fileName));
I am currently working in Unity3D and wish to simply open a .txt file upon clicking on a button.
EDIT : When I say open a .txt file, I mean open it in some editor on the device, not open it asnd save it's content to some string in my app. Kind of like opening a browser to access a website from the app.
Here's the code I currently have (C#) :
private void ShowTextFile(string fileName)
{
Application.OpenURL(Application.streamingAssetsPath + "/PATH/" + fileName);
}
But it's not working ! What am I missing ?
EDIT : I'm expecting for the .txt file to open in another window (like opening a web browser, for example), but it simply isn't doing anything. Not even getting an error.
EDIT2 : I tried using Application.persistentDataPath instead, and in both cases, it says my .txt file doesn't exist. However, when using Application.persistentDataPath, it opens up a message box asking me what I want to open the file with. Whatever I choose, it will give me an error, telling me error loading file or something like that. I've also noticed that it opens "file:///". Is it normal that there is a file:/// before the path ?
EDIT3 (I'm on fire !) : I think the problem might be related to the fact that there is a "." in my path (the com.me.myapp in the data path). Is there any way to avoid this ? Am I even looking at the right path ?
I've tried opening a txt file on Android before, using this:
TextAsset txt = (TextAsset)Resources.Load("file", typeof(TextAsset));
string content = txt.text;
Where file is the name of the txt file (don't need to write file.txt).
The variable string will contain the contents of the text file, you just need to loop through them afterwards.
This method requires:
using System.Text;
using System.IO;
Put file.txt inside a directory named "Resources" (inside Assets dir), if it isn't there then create a new one.
This is my code for Android:
var rpath = Path.Combine(Application.streamingAssetsPath, "file_name");
WWW www = new WWW(rpath);
yield return www;
StringReader streamReader = new StringReader(www.text);
text = streamReader.ReadToEnd();
For iOS:
var rpath = Path.Combine(Application.streamingAssetsPath, "file_name");
StreamReader streamReader = new StreamReader(rpath);
text = streamReader.ReadToEnd();
Note: file_name in StreamingAssets folder
Found a solution that works ! Here's the thing, the streaming assets path, on Android, returns a path that can only be read by a WWW object. So I simply read it with a WWW object then recreated the file in my persistent data path. Added a check to make sure the file doesn't already exist before creating it. Also, make sure you create the directory in case it doesn't exist, else you'll get an error. Note that this solution is probably not optimal if you have large files that are regularly accessed.
string realPath = Application.persistentDataPath + "/PATH/" + fileName;
if (!System.IO.File.Exists(realPath))
{
if (!System.IO.Directory.Exists(Application.persistentDataPath + "/PATH/"))
{
System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/PATH/");
}
WWW reader = new WWW(Application.streamingAssetsPath + "/PATH/" + realPath);
while ( ! reader.isDone) {}
System.IO.File.WriteAllBytes(realPath, reader.bytes);
}
Application.OpenURL(realPath);
If anyone has anything to add to this answer, feel free !
I use to store document/file in byte[] in database, and I want user can view/run that file from my application.
You need to know the file extension for the file you're writing, so the OS can run the default program based on the extension. The code would be something like this:
byte[] bytes = GetYourBytesFromDataBase();
string extension = GetYourFileExtension(); //.doc for example
string path = Path.GetTempFileName() + extension;
try
{
using(BinaryWriter writer = new BinaryWriter(File.Open(path, FileMode.Create)))
{
writer.Write(yourBytes);
}
// open it with default application based in the
// file extension
Process p = System.Diagnostics.Process.Start(path);
p.Wait();
}
finally
{
//clean the tmp file
File.Delete(path);
}
You will need to store the file extension in the database too. If you don't have the file extension the problem becomes very difficult as you cannot rely on the operating system to work out which program to launch to handle the file.
You can use the following pattern:
Load data from database and save to file using the original file extension.
Start a new System.Diagnostics.Process that points to the saved file path.
As you have saved the file with the original file extension, the OS will look for a program that is registered for the extension to open the file.
As chibacity and Daniel suggest, storing the file extension in the db, and agreed -- storing the file extension, or at least some indicator that tells you the file type, is a good idea.
If these files are of a format of your own creation then you might also want to store information about which version of the file format the data is stored in. During development file formats are prone to changing, and if you don't remember which version you used to store the data then you have a hard job recovering the information.
The same problems are faced in object persistence generally.