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

前端 未结 4 1176
攒了一身酷
攒了一身酷 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:32

    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

提交回复
热议问题