How to ignore an exception and continue processing a foreach loop?
- by Barry Dysert
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);
}