C# - Saving a '.txt' File to the Project Root

泪湿孤枕 提交于 2019-12-04 02:47:39

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.
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!