删除文件,但访问被拒绝。

21

我有一个带有Entity Framework的MVC4应用程序。

我想要删除一个文件,但每次都会显示:

引发了类型为“System.UnauthorizedAccessException”的异常,但在用户代码中未被处理

附加信息:拒绝访问路径“G:\ Mijn Documents \ My Web Sites \ Lolabikes-Copy \ C#\ ContosoUniversity \ Images \”。

出错的代码是:System.IO.File.Delete(path);

这是方法:

public ActionResult DeleteFiles(int id)
        {           
                //var fileName = Path.GetFileName(id.FileName);

                var DirSeparator = Path.DirectorySeparatorChar;
                var path = Server.MapPath("~\\Images" + DirSeparator);// + fileName.Replace('+', '_')));
               var file = db.lolabikerPhotos.Find(id);               
               System.IO.File.Delete(path);
               db.SaveChanges();           

            return Redirect(Url.Action("Edit", "Account") + "#tabs-3");

        }

我只是在Visual Studio中运行了这个应用程序,就像这样:http://localhost:41787/Account/Edit?UserId=hallo

我已经完成了以下工作:

对地图进行了完全访问,我将网络服务添加到具有完全控制权限的地图中。但似乎没有任何作用。我使用的是Windows 7,并且以管理员身份运行Visual Studio 2013。

我还看到了这个:

ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating. If the application is impersonating via <identity impersonate="true"/>, the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.

您可以在这里查看访问权限:

输入图像说明

我尝试类似于这样的东西:

 <system.web>

    <identity impersonate="true" userName="Administrator" password="windowsPassword"/>
    <httpRuntime requestValidationMode="2.0"  maxRequestLength="1048576" executionTimeout="3600" />
    <compilation debug="true" targetFramework="4.5" />

    <pages validateRequest="false" />

    <!--<httpRuntime targetFramework="4.5" />-->


  </system.web>

我已经添加了这个:

<identity impersonate="true" userName="Administrator" password="windowsPassword"/> 

好的,我可以运行该应用程序,但仍会出现错误:

Access to the path 'G:\Mijn Documents\My Web Sites\Lolabikes - Copy\C#\ContosoUniversity\Images\' is denied.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.UnauthorizedAccessException: Access to the path 'G:\Mijn Documents\My Web Sites\Lolabikes - Copy\C#\ContosoUniversity\Images\' is denied. 

ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating. If the application is impersonating via <identity impersonate="true"/>, the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user. 

To grant ASP.NET access to a file, right-click the file in File Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.

Source Error: 


Line 489:                var path = Server.MapPath("~\\Images" + DirSeparator);// + fileName.Replace('+', '_')));
Line 490:               var file = db.lolabikerPhotos.Find(id);               
Line 491:               System.IO.File.Delete(path);
Line 492:               db.SaveChanges();           
Line 493:

完全权限:

enter image description here

高级选项卡: enter image description here

已更改权限选项卡:

enter image description here

我将我的操作方法编辑成这样:

 public ActionResult DeleteFiles(int id)
        {           
                var fileName = Path.GetFileName(@"\\Koala.jpg");

                var DirSeparator = Path.DirectorySeparatorChar;
                var path = Server.MapPath(@"\\Images" + DirSeparator + fileName.Replace('+', '_'));
               var file = db.lolabikerPhotos.Find(id);
               LolaBikePhoto lola = db.lolabikerPhotos.Find(id);
               db.lolabikerPhotos.Remove(lola);
               System.IO.File.Delete(path);


               db.SaveChanges();           

            return Redirect(Url.Action("Edit", "Account") + "#tabs-3");

        }

现在它正在运作!


进入要授权访问的文件夹属性中的权限选项卡。获取该文件夹的所有权并将更改传播到所有子文件夹和文件。然后向每个人授予完全权限,并传播这些更改。确保应用所有更改。一旦验证它可以正常工作,您就可以重新保护您的权限。如果您需要帮助进行任何权限更改,有很多相关文章(只需谷歌搜索)。 - Jonathan Gray
我已经完成了,看看我的帖子。 - Niels Savant
网络服务权限没用。试着将权限授予普通用户。同时,确保它设置子文件夹和文件的权限。 - Jonathan Gray
我只是将文件存储在G盘上,而不是在Inetpub中拥有该项目,这会产生影响吗?但是该站点正在运行,只是删除无法正常工作(被拒绝)。 - Niels Savant
1
我只是粗略地浏览了你的问题,但无论你在做什么,都可能过于复杂了。在IIS中,在“身份验证”下,将“匿名身份验证”设置为“应用程序池标识”,然后将目录的权限授予应用程序池正在运行的用户。理想情况下,您希望为应用程序池使用托管服务帐户,以便轻松设置对网络共享的权限,但这不是必需的。 - user247702
显示剩余14条评论
3个回答

69
我也遇到了这个问题,所以我偶然发现了这篇文章。在复制/删除之前和之后,我添加了以下代码行。

删除


删除

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

复制

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

好的,但是请看一下我的帖子,它已经起作用了,我所做的事情,但是你的解决方案可能会改进一些东西,我会尝试一下。 - Niels Savant
2
不可能。这不能是对原帖的答案吧?你给文件夹完全的NETWORK_SERVICE访问权限,而不仅仅是文件,所以它应该能够删除文件。这里肯定有其他问题。 - Fandango68
那么这就是被接受的解决方案了吗?你通过设置FileAttributes解决了UnauthorizedAccessException问题? - Michael Starkie
我尝试使用这个方法进行删除,但是当我尝试设置属性时,出现了“UnauthorizedAccessException”错误。 - Lukas

6

在之前的回答基础上 - 对于我来说,我需要将文件夹及其内部的文件设置为普通属性。

    DirectoryInfo directory = new DirectoryInfo("/path/to/file");
    directory.Attributes = FileAttributes.Normal;

    foreach (FileInfo file in directory.GetFiles()) {
        file.Attributes = FileAttributes.Normal;
    }

0
foreach (string temp_dir in Directory.GetDirectories(temp_root)) { }
                        File.SetAttributes(temp_dir, FileAttributes.Normal);

                        // add true param because you need to use recursive for deleting first the content then the entire dir
                        // otherwise you'll get System.UnauthorizedAccessException
                        Directory.Delete(temp_dir, true); 
                    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接