C# - Saving a '.txt' File to the Project Root
File.WriteAllText requires two parameters:
The first one is the FileName and the second is the content to write
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + @"\" + fileName,
saveScene.ToString());
Keep in mind however that writing to the current folder could be problematic if the user running your application has no permission to access the folder. (And in latest OS writing to the Program Files is very limited). If it is possible change this location to the ones defined in Environment.SpecialFolder enum
I wish also to suggest using the System.IO.Path class when you need to build paths and not a string concatenation where 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());
no need for the extra + @"\"
just do:
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 on File.WriteAllText
here:
Parameters
path Type: System.String The file to write to. contents Type: System.String The string to write to the file.