windows C#,处理文件,“未经授权的访问”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4530413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 15:51:16  来源:igfitidea点击:

C#, working with files, "Unauthorized Access"?

c#windowsfile-permissions

提问by Rob

I'm learning about opening and saving files with C# and it seems that vista won't let my program save to a file on the root of C:\ , unless I run it in administrator mode.

我正在学习使用 C# 打开和保存文件,似乎 vista 不会让我的程序保存到 C:\ 根目录下的文件中,除非我在管理员模式下运行它。

Any ideas how to allow my program to play around with whatever files it wants?

任何想法如何让我的程序播放它想要的任何文件?

Thanks!

谢谢!

private string name;

private void open_Click(object sender, EventArgs e)
{
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        name = openFileDialog1.FileName;
        textBox1.Clear();
        textBox1.Text = File.ReadAllText(name);
        textBox2.Text = name;
    }
}

private void save_Click(object sender, EventArgs e)
{
    File.WriteAllText(name, textBox1.Text);
}

回答by jakobbotsch

To make your program start with administrator rights, you have to change the manifest. This can be done by Add New Item -> General -> Application Manifest File. Open the manifest and set "requestedExecutionLevel" to "requireAdministrator". When this is done, open the project settings and on the 'Application' tab choose your new manifest.

要使您的程序以管理员权限启动,您必须更改清单。这可以通过添加新项目 -> 常规 -> 应用程序清单文件来完成。打开清单并将“requestedExecutionLevel”设置为“requireAdministrator”。完成后,打开项目设置并在“应用程序”选项卡上选择您的新清单。

回答by Oded

The program will run with your credentials, by default.

默认情况下,该程序将使用您的凭据运行。

So, these do not have the right permissions to write to the root folder.

因此,这些没有写入根文件夹的正确权限。

If you want it to run with other credentials you can us the runascommand line to execute the application with other credentials.

如果您希望它使用其他凭据运行,您可以使用runas命令行使用其他凭据执行应用程序。

Alternatively, grant more permissions to the account the application runs as.

或者,向运行应用程序的帐户授予更多权限。

回答by user229263

There are several reasons for the UnauthorizedAccess Exception. Check one of those:

UnauthorizedAccess Exception 有多种原因。检查其中之一:

  • path specified a file that is read-only.

  • This operation is not supported on the current platform.

  • path specified a directory.

  • path 指定了一个只读文件。

  • 当前平台不支持此操作。

  • path 指定了一个目录。

I accidently hit the third problem today ;-)

我今天不小心碰到了第三个问题;-)