Debugging System.UnauthorizedAccessException (often followed by: Access to the path is denied)

It's time for another post in our series about Debugging common .NET exceptions. Today, I want to introduce you to System.UnauthorizedAccessException. The exception is typically caused by an IO error, but other issues like security restrictions are also known to utilize this error. Let's dig in!

Handling the error

Catching the exception is straightforward. Let's create a small program to provoke and catch this error. Before writing code, I'll create a text file named c:\temp\readonly.txt. Once created, right click the file, select Properties and enable the Read-only checkbox. This causes, surprise!, the file to be read-only. Now for the code:

class Program
{
    static void Main(string[] args)
    {
        var path = "c:\\temp\\readonly.txt";
        try
        {
            File.Delete(path);
        }
        catch (UnauthorizedAccessException e)
        {
            Console.WriteLine(e);
        }
    }
}

As shown in the code, we simply catch the UnauthorizedAccessException and log it to the console.

Debugging the error

UnauthorizedAccessException contains no additional status or error code property so that you can figure out what is going on. The only indication is to look in the Message property, which in most cases looks similar to this:

Access to the path 'c:\temp\notfound.txt' is denied.

So, why is access denied? We can start by excluding some scenarios I've seen people suggest as wrong answers on StackOverflow:

  1. If a file was not found on disk (this doesn't throw the UnauthorizedAccessException).
  2. If a file is currently locked by another program (this throws an IOException).
  3. If a file is being blocked by Windows.
  4. Accessing a file in a non-existing directory (this throws a DirectoryNotFoundException).

The following sections point out different causes of the exception.

Would your users appreciate fewer errors?

➡️ Reduce errors by 90% with elmah.io error logging and uptime monitoring ⬅️

A read-only file

Probably the easiest thing to check when dealing with files, is to right click the file and check if the Read-only checkbox is checked:

Simply uncheck Read-only and try again.

If you want to, you can unlock a read-only file in C# and try again:

class Program
{
    static void Main(string[] args)
    {
        var path = "c:\\temp\\notfound.txt";
        try
        {
            File.Delete(path);
        }
        catch (UnauthorizedAccessException)
        {
            FileAttributes attributes = File.GetAttributes(path);
            if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
            {
                attributes &= ~FileAttributes.ReadOnly;
                File.SetAttributes(path, attributes);
                File.Delete(path);
            }
            else
            {
                throw;
            }
        }
    }
}

Current user doesn't have access to a file

Another instance of the UnauthorizedAccessException is caused by issues with the user executing the program. If not running in elevated mode (Admin rights in Windows), the current user won't have access to various Windows directories like c:\Windows and c:\Program Files. A simple fix for this error is to run the program as Administrator.

If the error is generated by a Windows Service, open Services, locate your service on the list and double-click it. On the Log On tab, make sure your service is configured with a user with access to the resource causing the exception. Services running as Network Service have very limited access to local resources. I would recommend you chat with your systems administrator to decide if you want to go with the default service users or create a custom one with custom permissions.

Access to file system from IIS

If you are experiencing this error while browsing a website hosted on IIS, it's a similar error to the one described above. A .NET application hosted on IIS, uses the application pool user as a default to access files on the file system.

To fix this, add the IIS AppPool user to the root folder of your application by right clicking the folder and selecting Properties. Select the Security tab and add the IIS AppPool\<AppPoolName> user:

Like Windows Services, you can also decide to create a custom user to access the file system from IIS. Create a new Windows (or AD) user and click your site inside the IIS Manager. From the Actions window click Basic Settings. Finally, click the Connect as button and input the new user below Specific user:

This example illustrates the scenario where the IIS user doesn't have access to the folder containing the website files. You may also experience other scenarios where Windows authentication is used to control individual website users access to one or more files on the file system. In these cases, you want to re-use the example above to catch the exception in your code and inform the website user in a better way than showing an IIS error page.

Also make sure to read the other posts in this series: Debugging common .NET exception.

Features steps
We monitor your websites

We monitor your websites

We monitor your websites for crashes and availability. This helps you get an overview of the quality of your applications and to spot trends in your releases.

We notify you

We notify you

We notify you when errors starts happening using Slack, HipChat, mail or other forms of communication to help you react to errors before your users do.

We help you fix bugs

We help you fix bugs

We help you fix bugs quickly by combining error diagnostic information with innovative quick fixes and answers from Stack Overflow and social media.

See how we can help you monitor your website for crashes Monitor your website