gpt4 book ai didi

c# - 如何过滤具有特定扩展名的 Directory.EnumerateFiles

转载 作者:行者123 更新时间:2023-11-30 14:50:42 27 4
gpt4 key购买 nike

我想要一个文件夹中所有 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")))

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

最佳答案

这是通配符在文件搜索中的使用记录/默认行为。

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)

关于c# - 如何过滤具有特定扩展名的 Directory.EnumerateFiles,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36135418/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com