Question

I'm trying to iterate over the items on my start menu, but I keep receiving the UnauthorizedAccessException. I'm the directory's owner and my user is an administrator.

Here's my method (it's in a dll project):

// root = C:\Users\Fernando\AppData\Roaming\Microsoft\Windows\Start Menu
private void walkDirectoryTree(DirectoryInfo root) {
    try {
        FileInfo[] files = root.GetFiles("*.*");
        foreach (FileInfo file in files) {
            records.Add(new Record {Path = file.FullName});
        }
        DirectoryInfo[] subDirectories = root.GetDirectories();
        foreach (DirectoryInfo subDirectory in subDirectories) {
            walkDirectoryTree(subDirectory);
        }
    } catch (UnauthorizedAccessException e) {
        // do some logging stuff
        throw; //for debugging
    }
}

The code fail when it starts to iterate over the subdirectories. What else should I do? I've already tried to create the manifest file, but it didn't work. Another point (if is relevant): I'm just running some unit tests with visual studio (which is executed as administrator).

Was it helpful?

Solution

Based on your description, it appears there is a directory to which your user does not have access when running with UAC enabled. There is nothing inherently wrong with your code and the behavior in that situation is by design. There is nothing you can do in your code to get around the fact that your account doesn't have access to those directories in the context it is currently running.

What you'll need to do is account for the directory you don't have access to. The best way is probably by adding a few extension methods. For example

public static FileInfo[] GetFilesSafe(this DirectoryRoot root, string path) {
  try {
    return root.GetFiles(path);
  } catch ( UnauthorizedAccessException ) {
    return new FileInfo[0];
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top