I used the following method which supports * whildcard. Here is the algorithm, it checks if the path contains *, then from the left side of the *, it gets the last \ and consider the left side of \ as the root for search.
For example, the following search will return all directories in 2nd level of depth under c:\test:
var result = GetDirectories("c:\test\*\*");
Here is the function:
string[] GetDirectories(string path)
{
var root = path;
if (root.IndexOf('*') > -1)
root = root.Substring(0, root.IndexOf('*'));
if (root.LastIndexOf('\\') > -1)
root = root.Substring(0, root.LastIndexOf('\\'));
var all = Directory.GetDirectories(root, @"*", SearchOption.AllDirectories);
var pattern = $"^{Regex.Escape(path).Replace("\\*", "[^\\\\]*")}$";
return all.Where(x => Regex.IsMatch(x, pattern, RegexOptions.IgnoreCase)).ToArray();
}
The function needs some exception handling, for example for cases the resolved root doesn't exist. But in my tests it worked well for the following examples:
"c:\test\*" → All directories under c:\test\ path
"c:\test\a*" → All a* directories under c:\test\ path
"c:\test\a*\b*" → All b* directories under c:\test\a* path
"c:\test\a*\b" → All b directories under c:\test\a* path
"c:\test\*\*" → All directories two level depth under c:\test