C # - saving .txt file in the project root

I wrote code that requires saving a text file. However, I need to save it for my project root so that anyone can access it, not just me.

The method in question here is:

private void saveFileToolStripMenuItem_Click(object sender, EventArgs e) { try { string fileName = Microsoft.VisualBasic.Interaction.InputBox("Please enter a save file name.", "Save Game"); if (fileName.Equals("")) { MessageBox.Show("Please enter a valid save file name."); } else { fileName = String.Concat(fileName, ".gls"); MessageBox.Show("Saving to " + fileName); System.IO.File.WriteAllText(saveScene.ToString(), AppDomain.CurrentDomain.BaseDirectory + @"\" + fileName); } } catch (Exception f) { System.Diagnostics.Debug.Write(f); } } 

Many have told me that using AppDomain.CurrentDomain.BaseDirectory will contain the dynamic location of the application’s storage location. However, when I do this, nothing happens and the file is not created.

Is there any other way to do this, or am I just misusing it?

+6
source share
2 answers

File.WriteAllText requires two parameters.
The first is FileName, and the second is the content for recording

 File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + @"\" + fileName, saveScene.ToString()); 

Remember, however, that writing to the current folder may be problematic if the user on which the application is running does not have permission to access the folder. (And in the latest version of the OS, there are very few program files). If possible, change this location to those defined in Environment.SpecialFolder enum

I also want to suggest using the System.IO.Path class when you need to create paths, rather than concatenating strings in which you use the very "OS specific" constant "\" to separate paths.

In your example, I would write

  string destPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,fileName); File.WriteAllText(destPath, saveScene.ToString()); 
+17
source

no need for extra + @"\" just:

 AppDomain.CurrentDomain.BaseDirectory + fileName 

and replace the parameters

 saveScene.ToString() 

and

 AppDomain.CurrentDomain.BaseDirectory + fileName 

your code should be:

 private void saveFileToolStripMenuItem_Click(object sender, EventArgs e) { try { string fileName = Microsoft.VisualBasic.Interaction.InputBox("Please enter a save file name.", "Save Game"); if (fileName.Equals("")) { MessageBox.Show("Please enter a valid save file name."); } else { fileName = String.Concat(fileName, ".gls"); MessageBox.Show("Saving to " + fileName); System.IO.File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + fileName, saveScene.ToString()); } } catch (Exception f) { System.Diagnostics.Debug.Write(f); } } 

you can read File.WriteAllText here :

Options

  path Type: System.String The file to write to. contents Type: System.String The string to write to the file. 
+5
source

Source: https://habr.com/ru/post/953865/


All Articles