I am using enumeratefiles to list all the files in a directory. Its throws an exception when it encounters a filename containing illegal characters and then stops the foreach loop that is listing the files. How can I make the foreach loop continue listing out filenames despite the exception? Any ideas?
Code:
try {
DirectoryInfo directory = new DirectoryInfo(targetPath);
IEnumerable<FileInfo> allfiles = directory.EnumerateFiles("*.*", SearchOption.AllDirectories);
foreach (FileInfo file in allfiles)
{
Console.WriteLine(file.Name);
}
}
catch (ArgumentException o)
{
Console.WriteLine("Error: {0}", o.Message);
}
You have the try catch around the
foreachloop. This means that if any one of the calls inside the loop fails your code will abort the rest of the loop.Change the code to be something like this:
You still should have the try … catch around the
EnumerateFilesin case that throws an error.