我正在尝试在按钮单击事件上写入文件,但在尝试这样做时出现未经授权的错误。
这是我的代码:
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))
不确定我做错了什么?有人可以帮忙吗?
谢谢
最佳答案
默认情况下,在 Windows 中,用户或用户启动的程序无法将文件写入 Windows 电脑上的每个位置。
也许尝试将文件保存到其他位置。 如果这对您来说还不够,那么您可能需要考虑以更高的权限级别运行您的程序
如果您只想为应用程序保存文件,则最佳位置是 AppData 文件夹。获取其路径的典型方法如下:
string path=Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)+"/MyApplicationFolder";
关于c# - 尝试将文件保存到目录时出现访问被拒绝错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48108350/