Is there a way of recover from an Exception in Directory.EnumerateFiles?

前端 未结 4 1159
攒了一身酷
攒了一身酷 2020-12-19 12:16

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

4条回答
  •  有刺的猬
    2020-12-19 12:23

    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 results = new List();
    string start = "c:\\";
    results.Add(start);
    Stack stack = new Stack();
    
    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);
    }
    

提交回复
热议问题