Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 906
Josh Avatar asked Apr 23 '10 15:04

Josh


2 Answers

You're looking for the Directory.GetFiles method:

Directory.GetFiles(path, "*" + search + "*", SearchOption.AllDirectories)
like image 82
SLaks Avatar answered Oct 03 '22 19:10

SLaks


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();
like image 26
LBushkin Avatar answered Oct 03 '22 18:10

LBushkin