How to ignore an exception and continue processing a foreach loop?

Posted by Barry Dysert on Stack Overflow See other posts from Stack Overflow or by Barry Dysert
Published on 2013-10-24T15:47:28Z Indexed on 2013/10/24 15:53 UTC
Read the original article Hit count: 129

Filed under:
|
|

I have a test program that is supposed to loop over all the files under C:. It dies when it hits the "Documents and Settings" folder. I'd like to ignore the error and keep looping over the remaining files. The problem is that the exception is thrown in the foreach, so putting a try/catch around the foreach will cause the loop to exit. And putting a try/catch after the foreach never fires (because the exception is thrown in the foreach). Is there any way to ignore the exception and continue processing the loop?

Here's the code:

static void Main(string[] args)
{
    IEnumerable<string> files = Directory.EnumerateFiles(@"C:\", "*.*",
                                SearchOption.AllDirectories);
    foreach (string file in files)  // Exception occurs when evaluating "file"
        Console.WriteLine(file);
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET