In .NET 4, there\'s this Directory.EnumerateFiles() method with recursion that seems handy.
However, if an Exception occurs within a recursion, how can I continue/recove
The call to Directory.EnumerateFiles(..)
will only set-up the enumerator, because of lazy-evaluation. It's when you execute it, using a foreach
that you can raise the exception.
So you need to make sure that the exception is handled at the right place so that the enumeration can continue.
var files = from file in Directory.EnumerateFiles("c:\\",
"*.*", SearchOption.AllDirectories)
select new
{
File = file
};
foreach (var file in files)
{
try
{
Console.Writeline(file);
}
catch (UnauthorizedAccessException uEx)
{
Console.WriteLine(uEx.Message);
}
catch (PathTooLongException ptlEx)
{
Console.WriteLine(ptlEx.Message);
}
}
Update: There's some extra info in this question