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

I am trying to create a simple Windows Explorer, for example a treeview in C #, but I get this error at runtime:

An unhandled exception of type "System.UnauthorizedAccessException" occurred in the mscorlib.dll file

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

The code that I use is exactly the same as in this example, Microsoft from the MS Tree View Example .

Why am I getting this error?

+4
source share
1 answer

The error is pretty clear; your code tries to enter a directory that you do not have access to - the directory c: \ $ Recycle.Bin \ S-1-5-18 (which, by the way, is the SID for the local system). It is very sad that in this example, MSDN assumes that your program will have access to all directories, which is not very realistic.

You can change your code to gracefully handle directories that it does not have access to (catch the exception and keep moving). For example: if we change this line of sample code:

subSubDirs = subDir.GetDirectories(); 

This is where I suspect you are getting this error:

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

This will gracefully handle the inability to get children of a particular folder. In this case, try-catch . We are trying to get directories in a folder, however, if there is a System.UnauthorizedAccessException exception, understand it and assume that there are no subdirectories.

To deal with the error, you may receive other errors in the application that are similar, for example, because the user clicked on a folder and is now trying to display the contents of the directory.

+8
source

Source: https://habr.com/ru/post/1486330/


All Articles