Recursively enumerate files and dirs in C#
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开发者_JS百科 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?
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];
}
}
精彩评论