Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting file, but is access denied

Tags:

I have an mvc4 application with entity framework.

I want to delete a file, but every time it says:

An exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll but was not handled in user code

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

by this line: System.IO.File.Delete(path);

This is the method:

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

        }

I just run the app in visual studio, like this: http://localhost:41787/Account/Edit?UserId=hallo

I have done already the following things:

Full access to the map, I added the Network Service to the map with full control. But nothing seems to work. I am using windows 7. And I run visual studio 2013 as administrator

I also see this:

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.

Here you can see the access:

enter image description here

I try something like this:

 <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>

I've added this:

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

OK, I can run the app, but still gives the error:

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:

full permission:

enter image description here

Advanced tab: enter image description here

Changed permissions tab:

enter image description here

I edited my action method like this:

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

        }

And now it is working!

like image 495
Niels Savant Avatar asked Oct 26 '14 19:10

Niels Savant


People also ask

How do you delete a file that won't delete?

One is simply using the delete option, and the other one is deleting files permanently. When you can't delete a file normally, you can delete undeletable files Windows 10 by selecting the target file or folder and then press Shift + Delete keys on the keyboard for a try.

How do I force delete a file as administrator?

You can press Windows + R keys on the keyboard, type cmd, and press Ctrl + Shift + Enter to run Windows Command Prompt as administrator. Step 2. Then input the command line and hit Enter to force delete the file in Windows 10 with CMD. The command line is like this: del c:\users\alisa\desktop\test.


2 Answers

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);
like image 150
G.Nader Avatar answered Oct 18 '22 11:10

G.Nader


Building upon the answer - For me I had to set the folder and the files inside it to normal attributes.

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

    foreach (FileInfo file in directory.GetFiles()) {
        file.Attributes = FileAttributes.Normal;
    }
like image 27
Thomas Bailey Avatar answered Oct 18 '22 11:10

Thomas Bailey