C# - 保存“名为.txt”文件到项目的根 [英] C# - Saving a '.txt' File to the Project Root

查看:309
本文介绍了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?

推荐答案

File.WriteAllText 需要两个参数。结果
第一个是文件名,第二个是内容写

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类当你需要建立在您使用非常的操作系统路径,而不是一个字符串连接具体的的恒\来单独的路径。

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”文件到项目的根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆