tags:

views:

59

answers:

1

On MacOS using Mono, when I list files and dirs with Directory.GetFiles() I get System.UnathorizedAcessException and it stops enumerating. Anyone knows how to make it continue or maybe a different approach to enum files

EDIT: I wrote my own method, seems to work.

        static void DirSearch(string sDir) {
        try {
            foreach (string d in Directory.GetDirectories(sDir)) {
                Console.WriteLine(d);
                foreach (string f in Directory.GetFiles(d, "*")) {
                    Console.WriteLine(f);
                }

                DirSearch(d);
            }
        } catch { }
        }

EDIT: I wonder will that code exit on the first exception?

+1  A: 

If you put a try/catch around the Directory.GetFiles(), you should just be able to go on with the next directory if it fails. You can even wrap this like this:

private string[] SafeGetFilesForDirectory(string directory)
{
    try
    {
        return Directory.GetFiles(directory);
    }
    catch (UnauthorizedAccessException)
    {
        return new string[0];
    }
}
Pieter
An unspecified `catch` is usually not a good idea. Just catch the exceptions you're worried about; in this case, `UnauthorizedAccessException`.
kevingessner
Yep, good one. Updated the code.
Pieter