How to scan a directory with wildcard with a speci

2019-06-19 00:53发布

问题:

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

  • The folder is located in C:\Program
  • Version2.* could be anything like Version2.33, Version2.1, etc.
  • That folder has a folder named Files in it

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.

回答1:

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.



回答2:

Try this

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

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