Home
C#
UnauthorizedAccessException
Updated May 7, 2024
Dot Net Perls
UnauthorizedAccessException. Your C# program has caused an UnauthorizedAccessException. What could cause this error and how could it be fixed? Learn how to handle this kind of exception safely.
This error can be caused by using a path that the operating system does not accept. For example, if we try to write to a system file that is part of the OS, this exception may occur.
Example. The statement in this code that uses StreamWriter is completely correct, but the underlying operating system does not allow modifications to the specified file path.
Part 1 In a using-statement, we try to write to a Windows system file (notepad.exe). This causes an UnauthorizedAccessException to occur.
using
StreamWriter
Part 2 We handle the error by catching it in a catch-block. We can catch Exception, or UnauthorizedAccessException (not IOException).
IOException
using System;
using System.IO;

class Program
{
    static void Main()
    {
        try
        {
            // Part 1: try to write a file at a path that cannot be written.
            using (StreamWriter writer = new StreamWriter(@"C:\Windows\notepad.exe"))
            {
            }
        }
        catch (UnauthorizedAccessException ex)
        {
            // Part 2: catch and print the error.
            Console.WriteLine(ex);
        }
    }
}
System.UnauthorizedAccessException: Access to the path 'C:\Windows\notepad.exe' is denied. at Microsoft.Win32.SafeHandles.SafeFileHandle.CreateFile... ... at Program.Main() in C:\Users\...\programs\consoletemp\Program.cs:line 11
Exception class. It is possible to catch UnauthorizedAccessException by just testing for Exception in a catch block. This is probably the easiest way to handle this error.
Exception
Info To fix this problem, a different path that is allowed by the underlying operating system should be used for writing files.
Summary. UnauthorizedAccessException is not a kind of IOException, but it can be handled by testing for the Exception base class. It indicates the OS does not allow writing to a file location.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 7, 2024 (new).
Home
Changes
© 2007-2025 Sam Allen