Possible to specify directory path with a wildcard?



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(plcDirs.Any())
{
    // ...
}

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);

MSDN:

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.

Question

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:

c:\test\di*

would match all files in the directories:

c:\test\dictionary\
c:\test\directory\
c:\test\dig\

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




Try this

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

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



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




Links



Tags