UnauthorizedAccessException cannot resolve Directory.GetFiles failure

Ric picture Ric · Sep 8, 2009 · Viewed 34.6k times · Source

Directory.GetFiles method fails on the first encounter with a folder it has no access rights to.

The method throws an UnauthorizedAccessException (which can be caught) but by the time this is done, the method has already failed/terminated.

The code I am using is listed below:

try
{
    // looks in stated directory and returns the path of all files found                
    getFiles = Directory.GetFiles(
        @directoryToSearch, 
        filetype, 
        SearchOption.AllDirectories);             
}
catch (UnauthorizedAccessException) 
{ 
}

As far as I am aware, there is no way to check beforehand whether a certain folder has access rights defined.

In my example, I'm searching on a disk across a network and when I come across a root access only folder, my program fails.

Answer

Fredrik Mörk picture Fredrik Mörk · Sep 8, 2009

In order to gain control on the level that you want, you should probably probe one directory at a time, instead of a whole tree. The following method populates the given IList<string> with all files found in the directory tree, except those where the user doesn't have access:

// using System.Linq
private static void AddFiles(string path, IList<string> files)
{
    try
    {
        Directory.GetFiles(path)
            .ToList()
            .ForEach(s => files.Add(s));

        Directory.GetDirectories(path)
            .ToList()
            .ForEach(s => AddFiles(s, files));
    }
    catch (UnauthorizedAccessException ex)
    {
        // ok, so we are not allowed to dig into that directory. Move on.
    }
}