dafie
dafie

Reputation: 1169

Get directories that match wildcard

Is it possible to get all folders that match pattern including wildcards? I have this folder structure:

C
....logs
........v1
............api1
............api2
........v2
............api1
............api2
........other

I would like to get all folders that match this pattern:

c:\logs\v*\api*

So I should get theese directories:

c:\logs\v1\api1
c:\logs\v1\api2
c:\logs\v2\api1
c:\logs\v2\api2

I tried with this:

Directory.GetDirectories(@"c:\logs\v*\api*");

but this gives me an exception:

System.IO.IOException: 'The filename, directory name, or volume label syntax is incorrect. : 'c:\logs\v*\api*''

I also tried this:

string directory = @"c:\logs\v*\api*";
string rootDirectory = Directory.GetDirectoryRoot(directory);
Console.WriteLine($"rootDirectory: {rootDirectory}");

string remainingPath = directory.Substring(rootDirectory.Length);
Console.WriteLine($"remainingPath: {remainingPath}");

var result = Directory.GetDirectories(rootDirectory, remainingPath);

Which gives an output:

rootDirectory: c:\
remainingPath: logs\v*\api*

But at the end, exception is thrown:

System.IO.IOException: 'The filename, directory name, or volume label syntax is incorrect. : 'c:\logs\v*''

Any ideas?

Upvotes: 0

Views: 499

Answers (1)

Progman
Progman

Reputation: 19570

Use the searchPattern argument of the GetDirectories() method to search for directories with a specific search pattern.

var result = Directory.GetDirectories(@"C:\logs\", "v*");

Adjust the start directory and search pattern for your needs.

You can also split the given string path into the root directory and search path and use them as arguments for the Directory.GetDirectories() method:

string directory = @"c:\logs\v*\api";
string rootDirectory = Directory.GetDirectoryRoot(directory);
//Console.WriteLine(rootDirectory);
string remainingPath = directory.Substring(rootDirectory.Length);
//Console.WriteLine(remainingPath);
var result = Directory.GetDirectories(rootDirectory, remainingPath);
    

Upvotes: 3

Related Questions