C# - 将".txt"文件保存到项目根目录

Com*_*guy 9 c# file save

我写了一些代码,要求我保存文本文件.但是,我需要将它保存到我的项目根目录,这样任何人都可以访问它,而不仅仅是我.

这是有问题的方法:

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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

许多人告诉我,使用AppDomain.CurrentDomain.BaseDirectory将包含应用程序存储位置的动态位置.但是,当我执行此操作时,没有任何反应,也没有创建文件.

有没有其他方法可以做到这一点,还是我只是完全错误地使用它?

Ste*_*eve 28

File.WriteAllText需要两个参数.
第一个是FileName,第二个是要写的内容

File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + @"\" + fileName, 
                  saveScene.ToString());
Run Code Online (Sandbox Code Playgroud)

但请记住,如果运行应用程序的用户无权访问该文件夹,则写入当前文件夹可能会出现问题.(在最新的OS编写程序文件非常有限).如果可以将此位置更改为Environment.SpecialFolder枚举中定义的位置

我还建议在需要构建路径时使用System.IO.Path类,而不是使用字符串连接,其中使用非常"特定"\"操作系统"的常量来分隔路径.

在你的例子中我会写

 string destPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,fileName);
 File.WriteAllText(destPath, saveScene.ToString());
Run Code Online (Sandbox Code Playgroud)


No *_*ame 5

不需要额外的+ @"\"只是做:

AppDomain.CurrentDomain.BaseDirectory + fileName
Run Code Online (Sandbox Code Playgroud)

并替换参数

saveScene.ToString()
Run Code Online (Sandbox Code Playgroud)

AppDomain.CurrentDomain.BaseDirectory + fileName
Run Code Online (Sandbox Code Playgroud)

你的代码应该是:

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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

你可以在File.WriteAllText 这里阅读:

参数

   path Type: System.String 

       The file to write to.  

   contents Type: System.String

       The string to write to the file.
Run Code Online (Sandbox Code Playgroud)