Stop implicit template in Directory.GetFiles ()

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

Also returns files such as foo.xml_ Is there a way to make it not do this, or will I have to write code to filter the return results.

This is the same behavior as dir *.xml on the command line, but different from searching *.xml in Windows Explorer.

+4
source share
2 answers

This is design behavior. From MSDN (see notes section and examples):

SearchPattern with a file extension of exactly three characters returns files with an extension of three or more characters, where the first three characters correspond to the file extension specified in searchPattern.

You can 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(); 
+4
source

due to the search method in 8.3 format. If you try to find "* .xm", you will 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"; })); 
+2
source

All Articles