Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List files in folder which match pattern

Tags:

c#

.net

directory

I need to list files in directory which match some pattern. I tried playing with Directory.GetFiles, but don't fully get why it behaves in some way.

1) For example, this code:

            string[] dirs = Directory.GetFiles(@"c:\test\", "*t");

            foreach (string dir in dirs)
            {
                Debugger.Log(0, "", dir);
                Debugger.Log(0, "", "\n");

            }

outputs this:

c:\test\11.11.2007.txtGif
c:\test\12.1.1990.txt
c:\test\2.tGift
c:\test\2.txtGif
c:\test\test.txt
...others hidden

You can see some files end with f but were still returned by query, why?

2) Also, this:

                string[] dirs = Directory.GetFiles(@"c:\test\", "*.*.*.txt");


                foreach (string dir in dirs)
                {
                    Debugger.Log(0, "", dir);
                    Debugger.Log(0, "", "\n");

                }

returns this:

c:\test\1.1.1990.txt
c:\test\1.31.1990.txt
c:\test\12.1.1990.txt
c:\test\12.31.1990.txt

But according to the documentation (http://msdn.microsoft.com/en-us/library/07wt70x2(v=vs.110).aspx) I think it had to return also this file which is in the directory:

11.11.2007.txtGif

since extension (in the query string) is 3 letters long, but it didn't. why? (when query extension is 3 letters long, doc says it will return extensions which start with specified extensions too, e.g., see Remarks).


Am I the only one who finds these results strange?

Is there any other approach you would recommend for using when one wants to list files in folder which match certain pattern?

User in my case may arbitrarily type some pattern, and I don't want to rely on method which I am unsure about the result (like it happened with GetFiles).


1 Answers

This is the way that the Windows API works - you will see the same results if you use the dir command in a command prompt. This does NOT use regular expressions! It's pretty obscure...

If you want to do your own filtering, you can do it like so:

var filesEndingInT = Directory.EnumerateFiles(@"c:\test\").Where(f => f.EndsWith("t"));

If you want to use regular expressions to match, you can do it thusly:

Regex regex = new Regex(".*t$");
var matches = Directory.EnumerateFiles(@"c:\test\").Where(f => regex.IsMatch(f));

I suspect that you will want to let the user type in a simplified form of pattern and turn it into a regular expression, e.g.

"*.t" -> ".*t$"

The regular expression to find all filenames ending in t is ".*t$":

.*t$

Regular expression visualization

Debuggex Demo

like image 152
Matthew Watson Avatar answered May 12 '26 15:05

Matthew Watson