Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Recurse Directories using Directory.GetFiles and search pattern

Tags:

c#

recursion

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

like image 970
Darren Young Avatar asked Dec 08 '25 22:12

Darren Young


1 Answers

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

like image 132
sehe Avatar answered Dec 11 '25 10:12

sehe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!