9

I need to get list of files on some drive with paths that matches specific pattern, for example FA\d\d\d\d.xml where \d is digit (0,1,2..9). So files can have names like FA5423.xml.

What is the most efficient name to do this?

bao
  • 111
  • 1
  • 2
  • 5
  • 1
    Does this answer your question? [C# - Regex - Matching file names according to a specific naming pattern](https://stackoverflow.com/questions/1601241/c-sharp-regex-matching-file-names-according-to-a-specific-naming-pattern) – Jim G. Oct 21 '21 at 14:47

3 Answers3

21

Are you using C# 3?

Regex reg = new Regex(@"^FA[0-9]{4}\.xml$");
var files = Directory.GetFiles(yourPath, "*.xml").Where(path => reg.IsMatch(path));
Phil Gan
  • 2,813
  • 2
  • 29
  • 38
  • `.Select(path => path)` is redundant. – Marcelo Cantos May 11 '10 at 10:02
  • oki... and now that I look again I should anchor the regex and there's no point in getting `*.*` either. – Phil Gan May 11 '10 at 10:07
  • @Phil Better to use EnumerateFiles as this http://stackoverflow.com/questions/3554559/regex-to-find-a-file-in-folder because of performance you could see difference in this http://stackoverflow.com/questions/5669617/what-is-the-difference-between-directory-enumeratefiles-vs-directory-getfiles – QMaster May 15 '14 at 16:28
6

You could do something like:

System.IO.Directory.GetFiles(@"C:\", "FA????.xml", SearchOption.AllDirectories);

Then from your results just iterate over them and verify them against your regex i.e. that the ? characters in the name are all numbers

James
  • 80,725
  • 18
  • 167
  • 237
2

Use the Directory API to find FA????.xml, and run the resulting list through a regex filter:

var fa = from f in Directory.GetFiles("FA????.xml")
         where Regex.Match(f, "FA\d\d\d\d\.xml")
         select f;
Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365