00101010 10101010
00101010 10101010

Reputation: 313

How to scan a directory with wildcard with a specific subdirectory

I was wondering what would be a good way to scan a directory that has characters you are not sure of.

For example, I want to scan

C:\Program\Version2.*\Files

Meaning

I know that I could do something like foreach (directory) if contains("Version2."), but I was wondering if there was a better way of doing so.

Upvotes: 7

Views: 5240

Answers (2)

Tommy Grovnes
Tommy Grovnes

Reputation: 4156

Try this

var pattern = new Regex(@"C:\\Program\\Version 2(.*)\\Files(.*)");

var directories = Directory.EnumerateDirectories(@"C:\Program", "*", 
                                                 SearchOption.AllDirectories)
                                                .Where(d => pattern.IsMatch(d));

Upvotes: 1

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

Directory.EnumerateDirectories accepts search pattern. So enumerate parent that has wildcard and than enumerate the rest:

  var directories = 
    Directory.EnumerateDirectories(@"C:\Program\", "Version2.*")
     .SelectMany(parent => Directory.EnumerateDirectories(parent,"Files"))

Note: if path can contain wildcards on any level - simply normalize path and split by "\", than collect folders level by level.

Upvotes: 9

Related Questions