tags:

views:

79

answers:

5

Hello All-

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? Thanks in advance.

-Josh

+2  A: 
 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

Muad'Dib
+4  A: 

You're looking for the Directory.GetFiles method:

Directory.GetFiles(path, "*" + search + "*", SearchOption.AllDirectories)
SLaks
+1  A: 

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();
LBushkin
+2  A: 
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.

Glennular
+1  A: 

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