21

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!

Ed Schwehm
  • 2,163
  • 4
  • 32
  • 55
Niels Savant
  • 315
  • 4
  • 6
  • 16
  • Most applications run under regular user access, regardless of whether your account is an administrator or not. Just want to make sure, you are definitely running the application itself as an admin? Also, make sure the file you're deleting doesn't have its read-only attribute set. – Jonathan Gray Oct 26 '14 at 19:38
  • I can upload the files, but not delete the files, I also checked the path and that is correct I run visual studio as adminstrator – Niels Savant Oct 26 '14 at 19:43
  • Go into the permissions tab in the properties of the folder you want to grant access to. Take ownership of the folder and propagate the changes to all subfolders and files. Then grant full permissions to everyone and propagate those changes as-well. Make sure you apply all changes. Once you verify that it works you can then re-secure your permissions. If you need help with any of the permissions changes there are plenty of articles about it (just Google) – Jonathan Gray Oct 26 '14 at 19:49
  • I have done that, see my post – Niels Savant Oct 26 '14 at 19:55
  • Network Service permissions won't help. Try granting the permissions to regular users. Also, make sure it sets the permissions on subfolders and files. – Jonathan Gray Oct 26 '14 at 19:58
  • I see you have an IIS Users account group. That may be the group which you need to apply permissions for. – Jonathan Gray Oct 26 '14 at 20:01
  • You have an unknown username or bad password error. Replace the credentials in the config file you've just shown me to reflect the actual username and password of the account that you would like to use. I would recommend creating a new user account specifically for the job, but you can use your own username and password as-well. – Jonathan Gray Oct 26 '14 at 20:24
  • I have correct that, see post – Niels Savant Oct 26 '14 at 20:24
  • It's clear what the solution is now. All you have to do is find the correct account to grant the permissions to and grant them. Again, make sure you select the checkbox to apply the changes to all subfolders and files. – Jonathan Gray Oct 26 '14 at 20:27
  • I am realy sad. userName="SAVANTKING-PC\savantKing" with password..etc so I add that in the webconfig I went to the map Images, I added the right account: SAVANTKING-PC\savantKing full access. Still not working?? – Niels Savant Oct 26 '14 at 20:37
  • oke, Makes it a different that I am not have the project in Inetpub? I am just store the file on the G disk. But the site is working, only delete doesnt work(denied) – Niels Savant Oct 26 '14 at 20:42
  • I have a feeling that you're not propagating the permissions correctly. I notice in the image you're posting that you're missing the Advanced button which allows you to make propagating changes. Navigate to the folder manually with windows explorer, right click it and go to properties. Then go to the permissions tab and click advanced. Make sure the permissions are what they are supposed to be and that you check the box that allows subfolders and files to inherit the permissions. – Jonathan Gray Oct 26 '14 at 20:47
  • Edit post, to show full permission – Niels Savant Oct 26 '14 at 20:58
  • Can you show me what it says in the Advanced screen? – Jonathan Gray Oct 26 '14 at 20:59
  • Thanks for your patience. Check the box to replace all child objects permissions with the permissions from this object, then click apply. If you start getting errors you'll need to go to the owner tab and do the same to first take ownership of the subfolders and files. Once you have done this everything should work fine. – Jonathan Gray Oct 26 '14 at 21:20
  • It is working, see my post!! – Niels Savant Oct 27 '14 at 08:54
  • 1
    I've only skimmed your question but whatever you're doing is probably overcomplicating things. In IIS, under *Authentication*, set *Anonymous Authentication* to *Application pool identity*. Then give permissions on the directory to the user that the application pool is running as. Ideally you want to use a Managed Service Account for your application pool, to make it easy to set permissions on network shares, but it's not required. – user247702 Oct 27 '14 at 09:03
  • oke, but this is important: var fileName = Path.GetFileName(@"\\hallo.jpg"); – Niels Savant Oct 27 '14 at 10:30
  • Possible duplicate of [How do I delete a directory with read-only files in C#?](http://stackoverflow.com/questions/611921/how-do-i-delete-a-directory-with-read-only-files-in-c) – Michael Freidgeim Mar 23 '17 at 03:18

2 Answers2

69

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);
G.Nader
  • 847
  • 7
  • 9
  • ok, but see my post it is working, what I have done, but your solution can maybe improve something, I will try it – Niels Savant Oct 27 '14 at 12:58
  • 2
    No way. This can't be the answer to the OP? You gave full NETWORK_SERVICE access to the folder and not just the files, and it should be able to delete the file. Something else is going on here – Fandango68 Apr 21 '17 at 02:16
  • So this is the accepted solution? You solved an UnauthorizedAccessException by setting FileAttributes? – Michael Starkie Apr 02 '19 at 18:28
  • I tried this for deleting but I get `UnauthorizedAccessException` when trying to set the attribute. – Lukas Apr 29 '22 at 13:47
6

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;
    }
Thomas Bailey
  • 191
  • 2
  • 6