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.
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.
using
-statement, we try to write to a Windows system file (notepad.exe). This causes an UnauthorizedAccessException
to occur.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.
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.