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?
The is the documented/default behaviour of the wildcard usage with file searching.
Directory.EnumerateFiles Method (String, String)
If the specified extension is exactly three characters long, the method returns files with extensions that begin with the specified extension. For example, "*.xls" returns both "book.xls" and "book.xlsx".
Your current approach of filtering twice is the right way.
The only improvement you can do is to ignore case in EndsWith
like:
x.EndsWith(".xml", StringComparison.CurrentCultureIgnoreCase)
It seems like you cant do it using EnumerateFiles for 3 characters extension, according to MSDN
Quote from the article above
When you use the asterisk wildcard character in a searchPattern such as ".txt", the number of characters in the specified extension affects the search as follows: If the specified extension is exactly three characters long, the method returns files with extensions that begin with the specified extension. For example, ".xls" returns both "book.xls" and "book.xlsx". In all other cases, the method returns files that exactly match the specified extension. For example, ".ai" returns "file.ai" but not "file.aif". 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.
Therefore using the .Where extension seems like the best solution to your problem
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With