Stop implicit wildcard in Directory.GetFiles()

string[] fileEntries = Directory.GetFiles(pathName, "*.xml");

Also returns files like foo.xml_ Is there a way to force it to not do so, or will I have to write code to filter the return results.

This is the same behavior as dir *.xml on the command prompt, but different than searching for *.xml in windows explorer.

Upvotes: 4

Views: 2764

Answers (2)

Ahmad Mageed
Ahmad Mageed

Reputation: 96487

This behavior is by design. From MSDN (look at the note section and examples given):

A searchPattern with a file extension of exactly three characters returns files having an extension of three or more characters, where the first three characters match the file extension specified in the searchPattern.

You could limit it as follows:

C# 2.0:

string[] fileEntries = Array.FindAll(Directory.GetFiles(pathName,  "*.xml"),
    delegate(string file) {
        return String.Compare(Path.GetExtension(file), ".xml", StringComparison.CurrentCultureIgnoreCase) == 0;
    });
 // or
string[] fileEntries = Array.FindAll(Directory.GetFiles(pathName,  "*.xml"),
    delegate(string file) {
        return Path.GetExtension(file).Length == 4;
    });

C# 3.0:

string[] fileEntries = Directory.GetFiles(pathName, "*.xml").Where(file =>
   Path.GetExtension(file).Length == 4).ToArray();
// or
string[] fileEntries = Directory.GetFiles(pathName, "*.xml").Where(file =>
    String.Compare(Path.GetExtension(file), ".xml",
        StringComparison.CurrentCultureIgnoreCase) == 0).ToArray();

Upvotes: 5

manji
manji

Reputation: 47978

it's due to the 8.3 search method of windows. If you try to search for "*.xm" you'll get 0 results.

you can use this in .net 2.0:

string[] fileEntries = 
Array.FindAll<string>(System.IO.Directory.GetFiles(pathName, "*.xml"), 
            new Predicate<string>(delegate(string s)
            {
                return System.IO.Path.GetExtension(s) == ".xml";
            }));

Upvotes: 3

Related Questions