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

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)

Tags:

C#

.Net