In C# how can I search through a Folder and its Subfolders to find files t开发者_运维百科hat match a string value. My string value could be "ABC123" and a matching file might be ABC123_200522.tif. Can an Array collect these?
You're looking for the Directory.GetFiles
method:
Directory.GetFiles(path, "*" + search + "*", SearchOption.AllDirectories)
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();
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
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.
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.
精彩评论