Konrad Viltersten
Konrad Viltersten

Reputation: 39190

Checking for exitence or counting files with a pattern and without a pattern

In later version of .NET, there's a neat way to check the number or existence of files with names that follow a pattern.

private int HowManyDonkeys(string path)
{
  return Directory.EnumerateFiles(path, "*donkey*");
}

private bool AreThereAnyDonkeys(string path)
{
  return Directory.EnumerateFiles(path, "*donkey*").Any();
}

However, I wonder how to turn it around and list the files that are not donkeys. One way to do it is to list all and subtract the number of unwanted ones but it's not so neat. Another way is to use LINQ and go like this.

Directory.EnumerateFiles(path, "*")
  .Count(name => name.Contains("anti-donkey"));

Directory.EnumerateFiles(path, "*")
  .Any(name => name.Contains("anti-donkey"));

Is there an even better way (i.e. one that let's me specify the filtering condition for the pattern as the opposite of the input?

Upvotes: 0

Views: 50

Answers (2)

Richard Schneider
Richard Schneider

Reputation: 35477

EnumerateFiles only allows simple DOS search (* and ?), no regex.

As other's have said, You could use LINQ but that is not your question.

Upvotes: 1

Nikita Shrivastava
Nikita Shrivastava

Reputation: 3018

Get the files:

var files = Directory.EnumerateFiles("C:\\").Where(x => !x.Contains("donkey")).ToList();

Get the count

int count= Directory.EnumerateFiles("C:\\").Count(x => !x.Contains("donkey"));

Upvotes: 1

Related Questions