Josh
Josh

Reputation: 1901

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?

Upvotes: 21

Views: 45026

Answers (6)

Glennular
Glennular

Reputation: 18215

void DirSearch(string sDir)
{
    try
    {
        foreach (string d in Directory.GetDirectories(sDir))
        {
            foreach (string f in Directory.GetFiles(d, sMatch))
            {
                lstFilesFound.Add(f);
            }
            DirSearch(d);
        }
    }
    catch (System.Exception excpt)
    {
        Console.WriteLine(excpt.Message);
    }
}

where sMatch is the criteria of what to search for.

Upvotes: 3

G. Maniatis
G. Maniatis

Reputation: 131

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

Upvotes: 0

Antony Koch
Antony Koch

Reputation: 2053

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);
    }
  }
}

Upvotes: 1

LBushkin
LBushkin

Reputation: 131676

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();

Upvotes: 7

SLaks
SLaks

Reputation: 887453

You're looking for the Directory.GetFiles method:

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

Upvotes: 77

Muad'Dib
Muad'Dib

Reputation: 29216

 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

Upvotes: 6

Related Questions