DEV Community

Cover image for Debugging System.UnauthorizedAccessException (often followed by: Access to the path is denied)
Thomas Ardal
Thomas Ardal

Posted on • Originally published at blog.elmah.io

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);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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.

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;
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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.

Would your users appreciate fewer errors?

elmah.io is the easy error logging and uptime monitoring service for .NET. Take back control of your errors with support for all .NET web and logging frameworks.

➡️ Error Monitoring for .NET Web Applications ⬅️

This article first appeared on the elmah.io blog at https://blog.elmah.io/debugging-system-unauthorizedaccessexception/

Top comments (0)