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

C# - Saving a #39;.txt#39; File to the Project Root(C# - 将“.txt文件保存到项目根目录)

本文介绍了C# - 将“.txt"文件保存到项目根目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是有问题的方法:

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 将包含应用程序存储位置的动态位置.但是,当我执行此操作时,什么也没有发生,也没有创建文件.

Many people told me that using AppDomain.CurrentDomain.BaseDirectory would contain the dynamic location of where the app was stored. However, when I execute this, nothing happens and no file is created.

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

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

推荐答案

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

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

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

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

我还希望建议使用 System.IO.Path 类 当您需要构建路径而不是字符串连接时,您使用非常 'OS specific' 常量 ""分隔路径.

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.

在你的例子中我会写

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

这篇关于C# - 将“.txt"文件保存到项目根目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C# - 将“.txt"文件保存到项目根目录

基础教程推荐