Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Directory.GetFiles with regex-like filter

Tags:

c#

I have a folder with two files:

  • Awesome.File.20091031_123002.txt
  • Awesome.File.Summary.20091031_123152.txt

Additionally, a third-party app handles the files as follows:

  • Reads a folderPath and a searchPattern out of a database
  • Executes Directory.GetFiles(folderPath, searchPattern), processing whatever files match the filter in bulk, then moving the files to an archive folder.

It turns out that I have to move my two files into different archive folders, so I need to handle them separately by providing different searchPatterns to select them individually. Please note that I can't modify the third-party app, but I can modify the searchPattern and file destinations in my database.

What searchPattern will allow me to select Awesome.File.20091031_123002.txt without including Awesome.File.Summary.20091031_123152.txt?

like image 954
Juliet Avatar asked Nov 03 '09 20:11

Juliet


2 Answers

If your were going to use LINQ then...

  var regexTest = new Func<string, bool>(i => Regex.IsMatch(i, @"Awesome.File.(Summary)?.[\d]+_[\d]+.txt", RegexOptions.Compiled | RegexOptions.IgnoreCase));
  var files = Directory.GetFiles(@"c:\path\to\folder").Where(regexTest);
like image 189
David Avatar answered Oct 15 '22 19:10

David


Awesome.File.????????_??????.txt

The question mark (?) acts as a single character place holder.

like image 8
Joel Coehoorn Avatar answered Oct 15 '22 19:10

Joel Coehoorn