tags:

views:

266

answers:

3

I'm getting a Unauthorized Access Exception

  • in a file wich I can delelete manually.
  • in a folder where I'm able to delete by code other files
  • and the file isn't marked as read only
  • besides, I'm using windows XP in an standalone PC and I have not assigned any permissions to the folder or the file.
  • any other process is using the file

If it helps, this is the code where the exception ocurr:

protected void DeleteImage(string imageName)
{
    if (imageName != null)
    {
        string f = String.Format("~/Images/{0}", imageName);
        f = System.Web.Hosting.HostingEnvironment.MapPath(f);
        if (File.Exists(f))
        {
            if (f != null) File.Delete(f);
        }
    }
}

Why could this happen?

A: 

If it's not read-only it's possible that it is currently in use by another process.

jpoh
A: 

You, the human user, have a login with certain rights. The Web server might have a different login with different rights. A user starting with IUSR_XXXX or some such thing. Make sure that user has rights to the directory.

Without more info on the context in which you are deleting the file, I assume that the Web server user has different rights to a file than you do.

William Crim
+1  A: 

Checking the obvious first...

When you open the file property and take a look at its security settings. Does the user running the code (i.e. if this is ASP.NET, Network Services / Domain Service Account) has access to actually delete the file? If it is not, then change it and try again.

Are you running as administrator when trying to delete this manually? If you are, then that's probably why you are able to delete it manually. Try deleting it as the account running your ASP.NET (I'm assuming it is ASP.NET since you are using System.Web.Hosting.HostingEnvironment.MapPath.)

If both failed, try to see if any other process is actually currently using this file. Good tool to find out is SysInternal Process Monitor. Filter it by path containing your filename and you should see if anything is using it. Terminate the process and try again.

Jimmy Chandra
+1 for the sysinternal tool (until now, I didn't know how to use any of the the sysinternal tools)
eKek0