Search code examples
visual-studio-2010ienumerableenumerateillegal-characters

Error: Illegal characters in path


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);
}

Solution

  • You have the try catch around the foreach loop. 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:

    foreach (FileInfo file in allfiles)
    {
        try
        {
            Console.WriteLine(file.Name);
        }
        catch (ArgumentException o)
        {
            Console.WriteLine("Error: {0}", o.Message);
        }
    }
    

    You still should have the try ... catch around the EnumerateFiles in case that throws an error.