System.UnauthorizedAccessException: Access to the path is denied

Technorati Tags:

I came across this pain in the ass error today...pretty common I guess.  I was trying to do a System.IO.File.Move (which is in essence a copy as we all know) and kept getting the error System.UnauthorizedAccessException: Access to the path is denied.

The code:

private void RenamePhysicalFile(string uploadedFileName)
{
    string existingFile = Path.Combine(SoePath, uploadedFileName);

    if (File.Exists(existingFile))
    {
        try
        {
            string newFile = Path.Combine(SomePath, existingFile.Replace(existingFile.Substring(0, existingFile.IndexOf("-")), someTestString));
            File.Move(existingFile, newFile);
        }
        catch (Exception ex)
        {
            ErrorLog("Image Copy Error: " + ex.ToString());
            throw new ApplicationException("There was an error during a rename(move) operation on the Saved Item upload file: " + existingFile + " error: " + ex.ToString());
        }
    }
    else
    {
        ErrorLog("File does not exist or path is invalid for at the following filepath: " + existingFile);
    }
}

The .Move tries to perform a delete of the file to be renamed then creates a new file with the new name.  Well, eventually after adding a slew of users to the NTFS permissions to that .jpg and giving users such as Network Service, pcname\aspnet, mydomain\myusername, and so on) and still kept getting this error, I finally resorted to fiddling around with the user/context running the app pool of my site in IIS. 

I changed the app pool identity in IIS 7 (advanced properties) to use LocalSystem instead of Network Service and it works fine now.  Even though network service had full rights and Network Service was the user running my app pool, it still did not have the ability to delete and create new files in that directory for whatever reason (if you know please do reply to this).

System user did have all the rights just like Network Service but for some reason, LocalSystem with the app pool works for this and not Network Service.  I am running Vista 64-but with IIS 7 and a .NET 3.5 web application which uses this app pool now configured to run using Local System.

iis_app_pool

Anyways, the problem is resolved, my website is running under the LocalSystem account instead when firing up the asp.net site and File.Move works great now.

Adios.

Print | posted on Monday, December 14, 2009 10:16 PM

Comments on this post

# re: System.UnauthorizedAccessException: Access to the path is denied

Requesting Gravatar...
thanks Man
its workes perfect
thanks again
Left by Ali on Jan 13, 2010 9:22 PM

Your comment:

 (will show your gravatar)
 
Please add 7 and 2 and type the answer here: