Alex Rivera | Logout

Using Directory.GetFiles with a regex in C#?

Asked 2011-12-09T09:34:39.877
43

I have this code:

string[] files = Directory.GetFiles(path, "......", SearchOption.AllDirectories)

What I want is to return only files which do NOT start with p_ and t_ and have the extension png or jpg or gif. How would I do this?

Edit
Report

1 Answer

93

Directory.GetFiles doesn't support RegEx by default, what you can do is to filter by RegEx on your file list. Take a look at this listing:

Regex reg = new Regex(@"^^(?!p_|t_).*");

var files = Directory.GetFiles(yourPath, "*.png; *.jpg; *.gif")
                     .Where(path => reg.IsMatch(path))
                     .ToList();
answered 2011-12-09T09:41:46.947

Your Answer