tags:

views:

750

answers:

2

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).

+3  A: 

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];
  }
}
JaredPar
Using extension methods was a nice solution to work around the exceptions. To get the "missing" entries on my start menu, I've followed the path pointed by the registry key 'HKLM\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell\ Folders\Common Start Menu'.Thnx!
Fernando
A: 

Where are you running the code from? Are you asking for any permissions?

The Roaming directory needs more permissions than the minimum set for code to be able to read/write from there.

Wilhelm
I'm running from a Visual Studio's test project. From my point of view, since I'm the directory owner, and in the administrators group, this could should run normally. Am I missing something?
Fernando