'How to collect all files in a Folder and its Subfolders that match a string

In C# how can I search through a Folder and its Subfolders to find files that match a string value. My string value could be "ABC123" and a matching file might be ABC123_200522.tif. Can an Array collect these?



Solution 1:[1]

You're looking for the Directory.GetFiles method:

Directory.GetFiles(path, "*" + search + "*", SearchOption.AllDirectories)

Solution 2:[2]

If the matching requirements are simple, try:

string[] matchingFiles = System.IO.Directory.GetFiles( path, "*ABC123*" );

If they require something more complicated, you can use regular expressions (and LINQ):

string[] allFiles = System.IO.Directory.GetFiles( path, "*" );
RegEx rule = new RegEx( "ABC[0-9]{3}" );
string[] matchingFiles = allFiles.Where( fn => rule.Match( fn ).Success )
                                 .ToArray();

Solution 3:[3]

 DirectoryInfo di = new DirectoryInfo("c:/inetpub/wwwroot/demos");
 FileInfo[] rgFiles = di.GetFiles("*.aspx");

you can pass in a second parameter for options. Also, you can use linq to filter the results even further.

check here for MSDN documentation

Solution 4:[4]

From memory so may need tweaking

class Test
{
  ArrayList matches = new ArrayList();
  void Start()
  {
    string dir = @"C:\";
    string pattern = "ABC";
    FindFiles(dir, pattern);
  }

  void FindFiles(string path, string pattern)
  {
    foreach(string file in Directory.GetFiles(path))
    {
      if( file.Contains(pattern) )
      {
        matches.Add(file);
      }
    }
    foreach(string directory in Directory.GetDirectories(path))
    {
      FindFiles(directory, pattern);
    }
  }
}

Solution 5:[5]

Adding to SLaks answer, in order to use the Directory.GetFiles method, be sure to use the System.IO namespace.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SLaks
Solution 2 LBushkin
Solution 3 Muad'Dib
Solution 4 Antony Koch
Solution 5 G. Maniatis