C# 为什么访问路径被拒绝?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8821410/
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-08-09 04:38:12  来源:igfitidea点击:

Why is access to the path denied?

c#asp.netiounauthorizedaccessexcepti

提问by nick gowdy

I am having a problem where I am trying to delete my file but I get an exception.

我在尝试删除文件时遇到问题,但出现异常。

if (result == "Success")
{
     if (FileUpload.HasFile)
     {
         try
         {
              File.Delete(Request.PhysicalApplicationPath + app_settings.login_images + txtUploadStatus.Text);
              string filename = Path.GetFileName(btnFileUpload.FileName);
              btnFileUpload.SaveAs(Request.PhysicalApplicationPath + app_settings.login_images + filename);
         }
         catch (Exception ex)
         {
               Message(ex.ToString());
         }
      }
}

Also I should note that the folder I am trying to delete from has full control to network services.

另外我应该注意,我试图从中删除的文件夹对网络服务具有完全控制权。

The full exception message is:

完整的异常消息是:

System.UnauthorizedAccessException: Access to the path 'C:\Users\gowdyn\Documents\Visual Studio 2008\Projects\hybrid\hybrid\temp_loginimages\enviromental.jpg' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.File.Delete(String path) at hybrid.User_Controls.Imgloader_Add_Edit_Tbl.btnUpdate_Click(Object sender, EventArgs e) in C:\Users\gowdyn\Documents\Visual Studio 2008\Projects\hybrid\hybrid\User_Controls\Imgloader_Add_Edit_Tbl.ascx.cs:line 242

System.UnauthorizedAccessException:拒绝访问路径“C:\Users\gowdyn\Documents\Visual Studio 2008\Projects\hybrid\hybrid\temp_loginimages\enviromental.jpg”。在 System.IO.__Error.WinIOError(Int32 errorCode, String MaybeFullPath) 在 System.IO.File.Delete(String path) 在 hybrid.User_Controls.Imgloader_Add_Edit_Tbl.btnUpdate_Click(Object sender, EventArgs e) 在 C:\Users\gowdyn\ Documents\Visual Studio 2008\Projects\hybrid\hybrid\User_Controls\Imgloader_Add_Edit_Tbl.ascx.cs:line 242

Any ideas?

有任何想法吗?

回答by Brissles

You need to modify the privileges of the folder you're trying to delete from/save to. Right-click on the containing folder and use the Security tab to permit modifyrights for the user your application runs under.

您需要修改要从中删除/保存到的文件夹的权限。右键单击包含的文件夹并使用“安全”选项卡允许修改应用程序运行所在的用户的权限。

回答by Arsen Mkrtchyan

When a user tries to connect to your Web site, IIS assigns the connection to the IUSER_ComputerNameaccount, where ComputerName is the name of the server on which IIS is running. By default, the IUSER_ComputerNameaccount is a member of the Guests group. This group has security restrictions. Try to grand access to IUSER_ComputerName to that folder

当用户尝试连接到您的网站时,IIS 将连接分配给IUSER_ComputerName帐户,其中 ComputerName 是运行 IIS 的服务器的名称。默认情况下,IUSER_ComputerName帐户是来宾组的成员。该组有安全限制。尝试对该文件夹的 IUSER_ComputerName 访问权限

Hereis very good described answer about IIS security

是关于 IIS 安全性的非常好的描述答案

Hope this helps

希望这可以帮助

回答by Manish Singh

I too faced the same problem when trying to do this after deployment at server:

在服务器上部署后尝试执行此操作时,我也遇到了同样的问题:

dirPath = Server.MapPath(".") + "\website\" + strUserName;
if (!Directory.Exists(dirPath))
{
    DirectoryInfo DI = Directory.CreateDirectory(dirPath);
}
string filePath = Server.MapPath(".") + "\Website\default.aspx";
File.Copy(filePath, dirPath + "\default.aspx", true);
File.SetAttributes(dirPath + "\default.aspx", FileAttributes.Normal);

I granted permission in IIS to other group including administrator and my problem got solved.

我在 IIS 中向包括管理员在内的其他组授予了权限,我的问题得到了解决。

回答by Ron H

The exception that is thrown when the operating system denies access because of an I/O error or a specific type of security error.

当操作系统因 I/O 错误或特定类型的安全错误而拒绝访问时引发的异常。

I hit the same thing. Check to ensure that the file is NOT HIDDEN.

我打了同样的东西。检查以确保文件未被隐藏。

回答by riaandl

I also had the problem, hence me stumbling on this post. I added the following line of code before and after a Copy / Delete.

我也遇到了这个问题,因此我在这篇文章上绊倒了。我在复制/删除之前和之后添加了以下代码行。

Delete

删除

File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);

Copy

复制

File.Copy(file, dest, true);
File.SetAttributes(dest, FileAttributes.Normal);

回答by Drakell

I had the same problem on a newly moved website on a shared server. Solved through the web host panel (DotNetPanel) setting true the "allow write permissions". So if you are in a shared server before reviewing all code worth taking a look at the server configuration and could save you a lot of time.

我在共享服务器上新移动的网站上遇到了同样的问题。通过 Web 主机面板 (DotNetPanel) 设置 true 的“允许写入权限”解决。因此,如果您在查看所有代码之前处于共享服务器中,则值得查看服务器配置,并可以为您节省大量时间。

回答by Kacho

Be aware that if you are trying to reach a shared folder path from your code, you dont only need to give the proper permissions to the physicial folder thru the security tab. You also need to "share" the folder with the corresponding app pool user thru the Share Tab

请注意,如果您尝试从代码访问共享文件夹路径,则不仅需要通过安全选项卡为物理文件夹授予适当的权限。您还需要通过“共享”选项卡与相应的应用程序池用户“共享”文件夹

回答by Andrew Edvalson

This is an old issue, but I ran into it while searching. Turns out that I was missing the actual filename component in the save path for SaveAs...

这是一个老问题,但我在搜索时遇到了它。原来我在 SaveAs 的保存路径中缺少实际的文件名组件...

string uploadPath = Server.MapPath("~/uploads");
file.SaveAs(uploadPath); // BAD
file.SaveAs(Path.Combine(uploadPath, file.FileName)); // GOOD

回答by Terry

I have found that this error can occur in DESIGN MODE as opposed to ? execution mode... If you are doing something such as creating a class member which requires access to an .INI or .HTM file (configuration file, help file) you might want to NOT initialize the item in the declaration, but initialize it later in FORM_Load() etc... When you DO initialize... Use a guard IF statement:

我发现此错误可能发生在 DESIGN MODE 而不是 ? 执行模式...如果你正在做一些事情,比如创建一个需要访问 .INI 或 .HTM 文件(配置文件,帮助文件)的类成员,你可能不想初始化声明中的项目,但稍后初始化它在 FORM_Load() 等中......当你初始化......使用保护 IF 语句:

    /// <summary>FORM: BasicApp - Load</summary>
    private void BasicApp_Load(object sender, EventArgs e)
    {
        // Setup Main Form Caption with App Name and Config Control Info
        if (!DesignMode)
        {
            m_Globals = new Globals();
            Text = TGG.GetApplicationConfigInfo();
        }
    }

This will keep the MSVS Designer from trying to create an INI or HTM file when you are in design mode.

这将阻止 MSVS 设计器在您处于设计模式时尝试创建 INI 或 HTM 文件。

回答by user3238433

Check your files properties. If the read-only is checked, uncheck it. This was my personal issue with the UnauthorizedAccessException.

检查您的文件属性。如果只读被选中,取消选中它。这是我对 UnauthorizedAccessException 的个人问题。