Is there any way to recover from Exception in Directory.EnumerateFiles?

In .NET 4, this Directory.EnumerateFiles () method exists with recursion, which seems convenient.
However, if an exception occurs in recursion, how can I continue / recover from this and continue to list the remaining 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); } 
+4
exception linq enumerate
Apr 01 '10 at 8:29
source share
4 answers

I have found a solution to this. Using the stack to display the results of an enumeration, you can really handle the exceptions. Here's a snippet of code: (inspired in 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); } 
+3
Sep 25 '10 at 21:16
source share

I had the same problem and implemented functionality. You can find the solution at http://rwtools.codeplex.com/ .

Inside are classes such as "DirectoryEnumerator" and "FileEnumerator," which ignores errors or (if anyone likes) throws an error and continues the iteration.

Hope this helps.

Regards, Sandro

+1
07 Oct '11 at 18:36
source share

I think this approach is not working properly. Although the UnauthorizedAccessException is caught, the iteration immediately ends when this happens. That way, you just get all the files that were received before the exception was thrown.

0
May 30 '10 at 9:28 a.m.
source share

A call to Directory.EnumerateFiles(..) will only result in a counter setting due to lazy evaluation. This is when you execute it using foreach , which you can throw an exception.

So, you need to make sure that the exception is handled in the right place so that the enumeration continues.

 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 is additional information in this matter

-2
Apr 01 '10 at
source share



All Articles