Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

Confused about Directory.GetFiles

I've read the docs about the Directory.GetPath search pattern and how it is used, because I noticed that *.dll finds both test.dll and test.dll_20170206. That behavior is documented

Now, I have a program that lists files in a folder based on a user-configured mask and processes them. I noticed that masks like *.txt lead to the above mentioned "problem" as expected.

However, the mask fixedname.txt also causes fixedname.txt_20170206 or the like to appear in the list, even though the documentation states this only occurs

When you use the asterisk wildcard character in a searchPattern such as "*.txt"

Why is that?

PS: I just checked: Changing the file mask to fixednam?.txt does not help even though the docs say

When you use the question mark wildcard character, this method returns only files that match the specified file extension. For example, given two files, "file1.txt" and "file1.txtother", in a directory, a search pattern of "file?.txt" returns just the first file, whereas a search pattern of "file*.txt" returns both files.

Upvotes: 14

Views: 1256

Answers (2)

Robert S.
Robert S.

Reputation: 2042

If you need a solution you may transform the filter pattern into a regular expression by replacing * by (.*) and ? by .. You also have to escape some pattern characters like the dot. Then you check each filename you got from Directory.GetFiles against this regular expression. Keep in mind to not only check if it is a match but that the match length is equal to the length of the filename. Otherwise you get the same results as before.

Upvotes: 2

Ravindra Sahasrabudhe
Ravindra Sahasrabudhe

Reputation: 11

GetFiles uses pattern serach, it searches for all names in path ending with the letters specified.

You can write code similar to below to get only .txt extension file

  foreach (string strFileName in Directory.GetFiles(@"D:\\test\","*.txt"))
            {
                string extension;
                extension = Path.GetExtension(strFileName);

                if (extension != ".txt")
                    continue;
                else
                {
                    //processed the file
                }
            }  

Upvotes: 1

Related Questions