rlartiga
rlartiga

Reputation: 485

How to count the number of matches of files in a directory

I was looking many questions after answering this.

How I find if in a directory exists at least one (and better if you give me the number of) files which matches a certain regular expression?

I know I can loop the files in the directory with this answer

But there is a way of counting without looping?

I try with count() but that don't work

Upvotes: 1

Views: 2216

Answers (3)

Brad
Brad

Reputation: 31

If the pattern is simple, then GetFiles in Directory already provides the information without using RegEx.

int count = Directory.GetFiles(@"c:\", "*.txt", SearchOption.AllDirectories).Count();

Upvotes: 3

Raidri
Raidri

Reputation: 17550

Taken from your linked question / answer, this should work:

int count = Directory.GetFiles(@"c:\temp").Count(path => Regex.IsMatch(path, pattern));

Upvotes: 3

mikey
mikey

Reputation: 5160

You can get them without the bottom foreach loop by using the Length property of the array returned by the Directory.GetFiles method.

int count = matches.Length;

http://msdn.microsoft.com/en-us/library/system.array.length.aspx

Upvotes: 2

Related Questions