How to check if a specific file exists in directory or any of its subdirectories

If you’re looking for a single specific filename, using *.* is indeed heavy handed. Try this:

var file = Directory.GetFiles(tempScanStorage, foo, SearchOption.AllDirectories)
                    .FirstOrDefault();
if (file == null)
{
    // Handle the file not being found
}
else
{
    // The file variable has the *first* occurrence of that filename
}

Note that this isn’t quite what your current query does – because your current query would find “xbary.txt” if you foo was just bar. I don’t know whether that’s intentional or not.

If you want to know about multiple matches, you shouldn’t use FirstOrDefault() of course. It’s not clear exactly what you’re trying to do, which makes it hard to give more concrete advice.

Note that in .NET 4 there’s also Directory.EnumerateFiles which may or may not perform better for you. I highly doubt that it’ll make a difference when you’re searching for a specific file (instead of all files in the directory and subdirectories) but it’s worth at least knowing about. EDIT: As noted in comments, it can make a difference if you don’t have permission to see all the files in a directory.

Leave a Comment