This page was last reviewed on 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.
Part 2 We handle the error by catching it in a catch-block. We can catch Exception, or UnauthorizedAccessException (not 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.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 7, 2024 (new).
© 2007-2024 Sam Allen.