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

The alternative is to write the search function yourself, one of these should work:

private bool FileExists(string rootpath, string filename)
{
    if(File.Exists(Path.Combine(rootpath, filename)))
        return true;

    foreach(string subDir in Directory.GetDirectories(rootpath, "*", SearchOption.AllDirectories))
    {
        if(File.Exists(Path.Combine(subDir, filename)))
            return true;
    }

    return false;
}

private bool FileExistsRecursive(string rootPath, string filename)
{
    if(File.Exists(Path.Combine(rootPath, filename)))
        return true;

    foreach (string subDir in Directory.GetDirectories(rootPath))
    {
        if(FileExistsRecursive(subDir, filename))
            return true; 
    }

    return false;
}

The first method still extracts all of the directory names and would be slower when there are many subdirs but the file is close to the top.

The second is recursive which would be slower in 'worst case' scenarios but faster when there are many nested subdirs but the file is in a top level dir.


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.

Tags:

C#