Reputation: 854
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
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