views:

461

answers:

2
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.

+3  A: 

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();
Ahmad Mageed
Any idea of the reason for this seemingly bizarre behaviour? Legacy 8.3 filename stuff?
Jon Seigel
I'm targeting the 2.0 framework so I can't use the => syntax.
Dan Neely
@Dan: updated code to use an anonymous delegate. @Jon Seigel: yep, that's correct. Another note on the MSDN link mentions that the method "checks against file names with both the 8.3 file name format and the long file name format."
Ahmad Mageed
Your first C#2.0 has a *.txt where it should be *.xml. Otherwise it does exactly what I needed. Thanks.
Dan Neely
@Dan: thanks, updated. I was testing locally with .txt files and missed it here :)
Ahmad Mageed
+2  A: 

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";
            }));
najmeddine