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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18813475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:16:53  来源:igfitidea点击:

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

c#filesave

提问by Computoguy

I have written some code which requires me to save a text file. However, I need to get it to save to my project root so anyone can access it, not just me.

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

Here's the method in question:

这是有问题的方法:

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 people told me that using AppDomain.CurrentDomain.BaseDirectorywould contain the dynamic location of where the app was stored. However, when I execute this, nothing happens and no file is created.

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

Is there another way of doing this, or am I just using it completely wrong?

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

采纳答案by Steve

File.WriteAllTextrequires two parameters:
The first one is the FileName and the second is the content to write

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

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.SpecialFolderenum

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

I wish also to suggest using the System.IO.Path classwhen you need to build paths and not a string concatenation where you use the very 'OS specific'constant "\"to separate paths.

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

In your example I would write

在你的例子中,我会写

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

回答by No Idea For Name

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.WriteAllTexthere:

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

Parameters

   path Type: System.String 

       The file to write to.  

   contents Type: System.String

       The string to write to the file.

参数

   path Type: System.String 

       The file to write to.  

   contents Type: System.String

       The string to write to the file.

回答by D J

Instead of using AppDomain.CurrentDomain.BaseDirectoryyou can just do it this way:

而不是使用AppDomain.CurrentDomain.BaseDirectory你可以这样做:

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

When you don't add anything, the basedirectory is automatically assumed.

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