djskj189
djskj189

Reputation: 295

SearchPattern for Directory.GetDirectories in C#

Desired search description:

Any string that contains either v2 or v3 (case insensitive)

I am trying to find subdirectory paths using Directory.GetDirectories(path, searchPattern), and I was going to supply the regex pattern for searchPattern argument, but apparently, searchPattern can't be regex expression.

Are there any other good ways to filter file names that contain v2 or v3?

Upvotes: 3

Views: 21016

Answers (3)

Mohammad Dayyan
Mohammad Dayyan

Reputation: 22458

According to https://learn.microsoft.com/en-us/dotnet/api/system.io.directoryinfo.getdirectories?view=netframework-4.7.2

searchPattern String
The search string to match against the names of directories. This parameter can contain a combination of valid literal path and wildcard (* and ?) characters, but it doesn't support regular expressions.

One filter:

DirectoryInfo di = new DirectoryInfo(@"d:\sources\");
DirectoryInfo[] dirs = di.GetDirectories("*my filter*");

Multiple filters:

DirectoryInfo di = new DirectoryInfo(@"d:\sources\");
DirectoryInfo[] dirs = di.GetDirectories("*", SearchOption.AllDirectories)
  .Where(q => q.Name.Equals("name1", StringComparison.InvariantCultureIgnoreCase) ||
              q.Name.Equals("name2", StringComparison.InvariantCultureIgnoreCase));

Upvotes: 0

haindl
haindl

Reputation: 3231

If you want to use a regex and avoid scanning the list of directories multiple times (to cut down the amount of necessary IO operations), you can do this:

var baseDir = "C:\\YourDirectory\\";
// Replace with your own Regex.
var dirNames = new Regex("v2|v3", RegexOptions.Compiled | RegexOptions.IgnoreCase);
var dirsFiltered =
    Directory.EnumerateDirectories(baseDir).Where(dir => dirNames.IsMatch(dir)).ToArray();

Upvotes: 9

Patrick Hofman
Patrick Hofman

Reputation: 157108

Directory.GetDirectories doesn't support regex, so you can't use that.

I would use this instead:

foreach (string dir in Directory.GetDirectories(baseDir, "*v2*")
                      .Concat(Directory.GetDirectories(baseDir, "*v3*"))
        )
{
}

Upvotes: 3

Related Questions