Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Directory.GetFiles with a regex in C#?

Tags:

c#

regex

file

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?

like image 374
grady Avatar asked Dec 09 '11 09:12

grady


People also ask

Can you call directory getFiles () with multiple filters?

[ VB.NET ] Net Framework will probably have Directory. getFiles method that supports multiple filters.

What is the name space used for regex in C?

Text. RegularExpressions namespace is a Regex class, which encapsulates the interface to the regular expressions engine and allows you to perform matches and extract information from text using regular expressions.

What is the namespace to be used for regular expressions?

C# provides a class termed as Regex which can be found in System. Text. RegularExpression namespace.


2 Answers

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(); 
like image 108
Abdul Munim Avatar answered Sep 18 '22 15:09

Abdul Munim


You can't stick a Regex into the parameter, it's just a simple string filter. Try using LINQ to filter out afterwards instead.

var files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)             .Where(s => s.EndsWith(".jpg") || s.EndsWith(".png"))             .Where(s => s.StartsWith("p_") == false && s.StartsWith("t_") == false) 
like image 25
Ian Avatar answered Sep 20 '22 15:09

Ian