I want to find all excel files within a directory structure using recursion. The problem is, the search pattern used in Directory.GetFiles only allows a single extension at a time.
Does anybody know a way around this or do I have to recurse through the directories multiple times looking for specific extensions? Or can you just grab every single file, and then loop through that list looking for specific extensions. Either way sounds a little inefficient.
Thanks
In .NET every version there is SearchOption.TopDirectoryOnly and SearchOption.AllDirectories
In .NET 4 you could very efficiently do e.g.:
var regex = new Regex(@"\d+", RegexOptions.Compiled);
var files = new DirectoryInfo(topdir)
.EnumerateFiles("*.*", SearchOption.AllDirectories)
.Where(fi => regex.IsMatch(fi.Name));
(This example filters for files having two digits in the name)
To emulate this, write a recursive enumerator method (yield return) to return all files, and filter the result like so:
IEnumerable<FileInfo> Recurse(string topdir)
{
// for each GetFiles() array element
// if is_not_dir yield return
// else Recurse(subdir)
}
var filtered = Recurse.Where(fi => regex.IsMatch(fi.Name));
HTH
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With