Take the 2-minute tour ×

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.

share|improve this question
add comment

1 Answer

up vote 5 down vote accepted

You have an overload for this which allows you to specify a search pattern or if you need to specify search options there's another overload:

foreach (string directory in Directory.GetDirectories(sourcePath, "di*"))
    // whatever
share|improve this answer
I believe that is a file filter and does not allow for use of wildcards when specifying the directory. Wouldn't your example only get files that start with di in a specific directory. –  Abe Miessler Sep 2 '11 at 16:31
@Abe Miessler, no, it works with directory names perfectly fine. Try the example I posted: Directory.GetDirectories(@"c:\test", "di*")) will match all the directories you have shown in your question. –  Darin Dimitrov Sep 2 '11 at 16:33
oh! Ok, let me test. –  Abe Miessler Sep 2 '11 at 16:34
Ahh, I was looking at GetFiles instead of GetDirectories. Thanks! –  Abe Miessler Sep 2 '11 at 16:51
add comment

Your Answer


