简体   繁体   English

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

[英]C#, working with files, “Unauthorized Access”?

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

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". 打开清单并将“requestedExecutionLevel”设置为“requireAdministrator”。 When this is done, open the project settings and on the 'Application' tab choose your new manifest. 完成此操作后,打开项目设置,然后在“应用程序”选项卡上选择新的清单。

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 runas command line to execute the application with other credentials. 如果您希望它与其他凭据一起运行,您可以使用runas命令行来执行具有其他凭据的应用程序。

Alternatively, grant more permissions to the account the application runs as. 或者,为应用程序运行的帐户授予更多权限。

There are several reasons for the UnauthorizedAccess Exception. UnauthorizedAccess异常有几个原因。 Check one of those: 检查其中一个:

  • path specified a file that is read-only. path指定了只读文件。

  • This operation is not supported on the current platform. 当前平台不支持此操作。

  • path specified a directory. path指定了一个目录。

I accidently hit the third problem today ;-) 我今天意外地遇到了第三个问题;-)

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

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