简体   繁体   English

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

[英]Access denied error when trying to save file to directory

I am trying to write a file on button click event but getting an unauthorized error when trying to do so. 我正在尝试在按钮单击事件中写入文件,但是在尝试这样做时遇到未授权的错误。

Here is my code: 这是我的代码:

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

Getting the error by: 通过以下方式获取错误:

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

Not sure what i am doing wrong? 不知道我在做什么错? Could someone please help? 有人可以帮忙吗?

Thanks 谢谢

By default in Windows a user or a programm started by a user can't write files to every location on a Windows pc. 默认情况下,在Windows中,用户或用户启动的程序无法将文件写入Windows pc上的每个位置。

Maybe try saving your file to a different location. 也许尝试将文件保存到其他位置。 If that doesn't cut it for you, then you may need to look into running your programm at an elevated permission level 如果那不适合您,那么您可能需要考虑以提升的权限级别运行程序

If you just want to save a file for your application the tippical place to do so would be the AppData Folder. 如果您只想为应用程序保存文件,最典型的保存位置是AppData文件夹。 The tipcal way of getting its path goes somthing like this: 获取路径的最主要方法是这样的:

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

您应该更改路径以授权文件夹,例如:

string path=Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM