Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll

Tags:

c#

I'm trying to create a simple windows-explorer like treeview in c#, however I am getting this error at runtime:

An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll

Additional information: Access to the path 'c:\$Recycle.Bin\S-1-5-18' is denied.

The code I'm using is exactly the same as this example by Microsoft from MS Tree View example.

Why am I getting this error?

like image 869
TK421 Avatar asked Feb 17 '23 05:02

TK421


1 Answers

The error is pretty clear; your code is trying to step into a directory that you don't have access to - the c:\$Recycle.Bin\S-1-5-18 directory (which, incidentally is the SID for Local System). It's rather unfortunate that this MSDN sample assumes that your program will have access to every single directory, which isn't very realistic.

You can change your code to gracefully handle directories it doesn't have access to (catch the exception and keep on going). For example: if we change this line of the code sample:

subSubDirs = subDir.GetDirectories();

Which is where I suspect you are getting that error to:

try
{
    subSubDirs = subDir.GetDirectories();
}
catch (System.UnauthorizedAccessException)
{
    subSubDirs = new DirectoryInfo[0];
}

This will gracefully handle not being able to get the children of a particular folder. This uses a try-catch statement. We try to get the directories in the folder, however if there is an System.UnauthorizedAccessException exception, catch it and assume there are no subdirectories.

That's the basic of handling an error, you may get other errors in your application that are similar, say because the user clicked the folder and now it is trying to show the directory's contents.

like image 126
vcsjones Avatar answered Mar 29 '23 23:03

vcsjones