C# treeview Unauthorized exception

1.1k views Asked by At

So I followed MS article http://msdn.microsoft.com/en-us/library/ms171645.aspx

This is Creating an Explorer Style Interface with the ListView and TreeView Controls Using the Designer.

So all is well, howerver, is you set it to the root of C to scan all the folders and files etc. I receive {"Access to the path '<path to file' is denied."}

VS 2010 points this spot that is the issue.

subSubDirs = subDir.GetDirectories();

I can put a try catch around this are, howerver, after the exception is thrown the app doesn't continue.

Is there a way I can skip directories that the app cannot access?

2

There are 2 answers

0
Nick Bray On BEST ANSWER

You might have the try catch in the wrong place. Based on the code in the walkthrough you could put the try catch like this:

Replace:

subSubDirs = subDir.GetDirectories();

with this:

try 
{
    subSubDirs = subDir.GetDirectories();
}
catch(UnauthorizedAccessException uae)
{
  //log that subDir.GetDirectories was not possible
}

Also, the line:

if (subSubDirs.Length != 0)

should be changed to:

if (subSubDirs != null && subSubDirs.Length != 0)
0
David Anderson On

You get the exception because the calling account doesn't have access rights to folders like System Volume Information. You can get around this some by using Linq and skipping folders that are marked System or Hidden.

DirectoryInfo root = new DirectoryInfo(@"C:\");

Func<FileSystemInfo, Boolean> predicate = dir =>
    (dir.Attributes & FileAttributes.System) != FileAttributes.System &&
    (dir.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden;

IEnumerable<FileSystemInfo> directories = root.GetDirectories().Where(predicate);

foreach (DirectoryInfo directory in directories) {
    try {
        Trace.WriteLine(directory.Name);
        DirectoryInfo[] subdirectories = directory.GetDirectories();
    }
    catch (System.UnauthorizedAccessException) {
        Trace.WriteLine("Insufficient access rights.");
    }
}

Trace.WriteLine("End of application.");

This is not solution for every scenario though, and will fail on some files and folders. There is no easy solution using the existing API; you may want to look into getting file and directory information through WMI instead.