How to filter Directory.EnumerateFiles with specific extension

Viewed 2589

I want a list of all xml files in a folder like this:

foreach (var file in Directory.EnumerateFiles(folderPath, "*.xml"))
{
    // add file to a collection
}

However, if I for some reason have any files in folderPath that ends with .xmlXXX where XXX represent any characters, then they will be part of the enumerator.

If can solve it easily by doing something like

foreach (var file in Directory.EnumerateFiles(folderPath, "*.xml").Where(x => x.EndsWith(".xml")))

But it seems a bit odd to me, as I basically have to search for the same thing two times. Is there any way to get the right files directly or am I doing something wrong?

3 Answers

Yes, and this design is stupid, stupid, stupid! It shouldn't do that. And it's annoying too!

That said, it appears this is what is happening: It actually searches both the long and short filenames. So files with longer extensions will have a short filename with the extension truncated to three characters.

And on newer versions of Windows, the short filenames may be disabled. So the behavior on newer systems will actually be what you would expect, and what it should've been in the first place.

Related