Unauthorized Access Exception DirectoryInfo.GetFiles() method

Gasta87 picture Gasta87 · Jun 3, 2013 · Viewed 7k times · Source

I wrote a program (on Windows 7) that call the method DirectoryInfo.GetFiles(), and in the folder "documents and settings", I have the exception of UnauthorizedAccess.

I tried lots of solutions, like:

create a manifest with


    `<requestedExecutionLevel level="highestAvailable" uiAccess="false" />`

and also with this

    DirectorySecurity dSecurity = Directory.GetAccessControl(dir.FullName);
    dSecurity.AddAccessRule(new FileSystemAccessRule("Luca", FileSystemRights.FullControl, AccessControlType.Allow));
    
    Directory.SetAccessControl(dir.FullName, dSecurity);

What could be the issue?

Answer

Matthew Brubaker picture Matthew Brubaker · Jul 25, 2013

First off, you should be using DirectoryInfo.EnumerateFiles(...) instead of GetFiles(...). EnumerateFiles(...) keeps you from having to get the entire list until you actually need to.

I ran into this issue a while back and found that I ended up needing to implement a replacement IEnumerable in order to be able to complete an enumeration over folders that I may only have selected access to.

You can see the result of my research in the following thread. DirectoryInfo.EnumerateFiles(...) causes UnauthorizedAccessException (and other exceptions)