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/recover from that and continuing enumerate the rest of the files?
try
{
var files = from file in Directory.EnumerateFiles("c:\\",
"*.*", SearchOption.AllDirectories)
select new
{
File = file
};
Console.WriteLine(files.Count().ToString());
}
catch (UnauthorizedAccessException uEx)
{
Console.WriteLine(uEx.Message);
}
catch (PathTooLongException ptlEx)
{
Console.WriteLine(ptlEx.Message);
}
I did found a solution to this. By using a stack to push the enumeration results, one can indeed handle the exceptions. Here's a code snippet: (inspired by this article)
List<string> results = new List<string>();
string start = "c:\\";
results.Add(start);
Stack<string> stack = new Stack<string>();
do
{
try
{
var dirs = from dir in Directory.EnumerateDirectories(
start, "*.*", SearchOption.TopDirectoryOnly)
select dir;
Array.ForEach(dirs.ToArray(), stack.Push);
start = stack.Pop();
results.Add(start);
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine(ex.Message);
start = stack.Pop();
results.Add(start);
}
} while (stack.Count != 0);
foreach (string file in results)
{
Console.WriteLine(file);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With