Possible to specify directory path with a wildcard?

2 Answers

Identify whether a subfolder starting with a certain string exists or not

You can use the overload of Directory.GetDirectories

string[] plcDirs = Directory.GetDirectories(@"C:\Test", "PLC*", SearchOption.TopDirectoryOnly);
    // ...

If there are many sub-directories it is more efficient to use the deferred executed EnumerateDirectories which does not need to load all into memory before it can start processing:

var plcDirs = Directory.EnumerateDirectories(@"C:\Test", "PLC*", SearchOption.TopDirectoryOnly);


The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names before the whole collection is returned; when you use GetDirectories, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient.


I have the following piece of code:

foreach (string file in Directory.GetFiles(sourcePath))
    // whatever

That gets files from a specific directory. Would it be possible to match directories using a wildcard? For example:


would match all files in the directories:


I saw that you can pass a file filter to the GetFiles method, but that applies to files only, not directory names.

Using the following, you can search folder and subfolders using searchpattern. It is most reliable, as GetAll sometimes fails when appropriate permissions is not correct.

Get all files and directories in specific path fast

Try this

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

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