尝试将文件保存到目录时访问被拒绝错误

时间:2018-01-05 06:30:55

标签: c#

我正在尝试在按钮点击事件上写一个文件,但在尝试这样做时会收到未经授权的错误。

这是我的代码:

private void button1_Click(object sender, EventArgs e)
    {
        {
            string path = @"c:\program files\MyTest.txt";
            if (!File.Exists(path))
            {
                // Create a file to write to.
                using (StreamWriter sw = File.CreateText(path))
                {
                    sw.WriteLine("Hello");
                }
            }

            // Open the file to read from.
            using (StreamReader sr = File.OpenText(path))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
            }
        }

通过以下方式获取错误:

using (StreamWriter sw = File.CreateText(path))

不确定我做错了什么?有人可以帮忙吗?

由于

2 个答案:

答案 0 :(得分:2)

默认情况下,在Windows中,用户启动的用户或程序无法将文件写入Windows PC上的每个位置。

也许尝试将文件保存到其他位置。 如果它没有为您剪切,那么您可能需要考虑在提升的权限级别运行您的程序

如果您只想为应用程序保存文件,那么这样做的地方就是AppData文件夹。获得它的路径的方法是这样的:

string path=Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)+"/MyApplicationFolder";

答案 1 :(得分:0)

您应该将路径更改为授权文件夹,如:

string path=Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
相关问题