als9xd
als9xd

Reputation: 854

Recursively search directories n directories deep

I'm looking for a way to find all files in a directory with a certain extension.

I'm using the following code:

string dir = "C:\temp"
FileInfo[] fsis = new DirectoryInfo(dir).GetFiles("*.cfg", SearchOption.AllDirectories);

The problem is that some directories contain many nested directories so it takes a very long time. Assuming that I know all .cfg files will only be up to n directories deep is there any way I can modify the above code to only search that far or will I have to write from scratch my own recursive file finder?

Upvotes: 3

Views: 245

Answers (1)

Nicholas Pipitone
Nicholas Pipitone

Reputation: 4142

List<FileInfo> FindFiles(List<FileInfo> results, string dir, int depth)
{
    // Get all cfg files in current directory
    results.AddRange(new DirectoryInfo(dir).GetFiles("*.cfg"));

    if(depth > 1)
    {
        // Recurse in all subdirectories
        foreach (DirectoryInfo d in new DirectoryInfo(dir).GetDirectories())
        {
            // But dont go as deep in those subdirectories
            FindFiles(results, d.FullName, depth - 1);
        }
    }
    return results;
}

And then you can call

List<FileInfo> = FindFiles(new List<FileInfo>(), "C:\Example", 5);

Upvotes: 3

Related Questions