如何使用特定扩展名过滤 Directory.EnumerateFiles

How to filter Directory.EnumerateFiles with specific extension

我想要一个文件夹中所有 xml 个文件的列表,如下所示:

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

但是,如果我出于某种原因在 folderPath 中有任何以 .xmlXXX 结尾的文件,其中 XXX 代表任何字符,那么它们将成为枚举器的一部分。

如果可以通过

这样的方式轻松解决
foreach (var file in Directory.EnumerateFiles(folderPath, "*.xml").Where(x => x.EndsWith(".xml")))

但这对我来说似乎有点奇怪,因为我基本上必须搜索相同的东西两次。有什么方法可以直接获取正确的文件还是我做错了什么?

根据 MSDN

,您似乎无法使用 EnumerateFiles 进行 3 个字符扩展

引自以上文章

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.

因此使用 .Where 扩展似乎是解决您问题的最佳方法

这是文件搜索中通配符用法的 documented/default 行为。

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

您目前的两次过滤方法是正确的。

您唯一可以做的改进是在 EndsWith 中忽略大小写,例如:

x.EndsWith(".xml", StringComparison.CurrentCultureIgnoreCase)

是的,这个设计是愚蠢的,愚蠢的,愚蠢的!它不应该那样做。而且也很烦人!

也就是说,这似乎是正在发生的事情:它实际上搜索长文件名和短文件名。因此,具有较长扩展名的文件将具有一个短文件名,扩展名被截断为三个字符。

并且在 Windows 的较新版本中,可能会禁用短文件名。因此,较新系统上的行为实际上将是您所期望的,并且首先应该是这样。