3

In my application I use the following command to get all files from a selected path:

foreach (string currentFile in Directory.EnumerateFiles(@"c:\", "*.*", SearchOption.AllDirectories))
{
    //some logic here
}

The thing is that when trying to access certain directories such as c:\Documents and Settings I get an UnauthorizedAccessException.

The folder mentioned above doesn't show in Windows Explorer or in the .NET System.Windows.Forms.FolderBrowserDialog and i can't find a specific attribute of this folder so I could filter the enumeration by.

I tried this and this but with no use.

Is there any kind of attribute or parameter I can use to restrict this kind of directories from my loop?

Community
  • 1
  • 1
Yoav
  • 3,326
  • 3
  • 32
  • 73
  • Windows Explorer simply doesn't list "Documents and Settings" because it's marked as a hidden system folder. It doesn't care whether it's accessible, if you configure Explorer to show hidden and system files and folders, it'll show up, but it'll still be inaccessible. –  Apr 09 '13 at 11:59

2 Answers2

3

Directory class does not provide a means to skip over inaccessible files and folders. You can write your own directory scanning method, that will recursively go into each folder and skip it if exception occurs.

alex
  • 12,464
  • 3
  • 46
  • 67
  • There's no way to check for this by checking the `DirectoryInfo` parameters? – Yoav Apr 09 '13 at 12:05
  • You can get access control list using DirectoryInfo.GetAccessControl() and then try to figure out if you have the permissions. But I see no reason for doing it, as catching exception would be easier to implement and understand. – alex Apr 09 '13 at 12:25
  • Ended up with this solution: http://stackoverflow.com/a/929418/1092181, apparently (and surprisingly) it is easier to catch the `exception` rather than checking for permissions. Thanks a lot! – Yoav Apr 25 '13 at 19:54
0

Can't you just get a Sys Admin to give your user read permissions to all the files? Sounds like there are things you can't access. Though I don't discourage you from solving this issue by excluding these files just from a portability standpoint(I can't speak directly to how to do this unfortunately).