正在删除文件,但访问被拒绝

问题描述 投票:0回答:3

我有一个带有实体框架的 mvc4 应用程序。

我想删除一个文件,但每次它都说:

mscorlib.dll 中发生“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.

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

enter image description here

我尝试这样的事情:

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

        }

现在它可以工作了!

c# windows entity-framework asp.net-mvc-4 visual-studio-2013
3个回答
69
投票

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

删除

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

复制

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

6
投票

基于答案 - 对我来说,我必须将文件夹 及其中的文件 设置为正常属性。

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

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

0
投票

foreach(Directory.GetDirectories(temp_root) 中的字符串 temp_dir) {

                        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); 
                    }
© www.soinside.com 2019 - 2024. All rights reserved.