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_
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();
You're looking for the Directory.GetFiles method:
Directory.GetFiles(path, "*" + search + "*", SearchOption.AllDirectories)
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
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);
}
}
}
Adding to SLaks answer, in order to use the Directory.GetFiles
method, be sure to use the System.IO
namespace.
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.