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

本文关键字:保存 项目 根目录 文件 txt | 更新日期: 2023-09-27 18:31:26

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

这是有问题的方法:

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);
        }
    }

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

有没有另一种方法可以做到这一点,或者我只是完全错误地使用它?

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

File.WriteAllText 需要两个参数:
第一个是文件名,第二个是要写入的内容

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

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

我还希望建议在需要构建路径时使用 System.IO.Path 类,而不是使用非常"特定于操作系统"的常量"'"来分隔路径的字符串串联。

在你的例子中,我会写

 string destPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,fileName);
 File.WriteAllText(destPath, saveScene.ToString());
不需要

额外的+ @"'"只需执行以下操作:

AppDomain.CurrentDomain.BaseDirectory + fileName

并替换参数

saveScene.ToString()

AppDomain.CurrentDomain.BaseDirectory + fileName

您的代码应该是:

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);
        }
    }

您可以在此处阅读File.WriteAllText

参数

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

与其使用 AppDomain.CurrentDomain.BaseDirectory,不如这样做:

    File.WriteLine("data''Mytxt.txt", "Success!");

当您不添加任何内容时,将自动假定基目录。