我希望搜索特定文件夹中的png文件,这些文件不是由给定的模式组成的,并将它们添加到列表框中。所以我想找到名字中没有_norm或_spec的pngs。Paterrn可以大写也可以小写。
文件夹中的文件:
希望得到的结果是:
a.png
发布于 2022-01-13 09:17:03
对于GetFiles,没有任何选项可以只排除要包含文件的模式,因此必须首先获得符合模式的所有文件,然后才能排除不需要的文件。
下面的方法排除了包含exclusions中提供的字符串之一的文件,并忽略了大小写:
Function ExcludeFiles(files As String(), exclusions As String()) As String()
Return files.Where(Function(s) Not exclusions.
Any(Function(e) s.IndexOf(e, StringComparison.CurrentCultureIgnoreCase) > 0)).
ToArray()
End Function用法:
Sub DoSomething()
Dim path As String = "C:\WhatEver"
Dim allPngFiles As String() = System.IO.Directory.GetFiles(path, "*.png")
Dim filtered As String() = ExcludeFiles(allPngFiles, {"_norm", "_spec"})
'Do something with the filtered files...
End Sub发布于 2022-01-13 08:24:40
您不能使用GetFiles进行筛选,因为它只能基于匹配的掩码进行筛选,而不是匹配它。您需要获取所有文件,然后通过适当的String比较丢弃不想要的文件。可能是这样的:
Dim folderPath = "folder path here"
Dim filePaths = Directory.GetFiles("*.png").
Where(Function(filePath)
Dim fileName = Path.GetFileNameWithoutExtension(filePath)
Return Not fileName.EndsWith("_norm", StringComparison.InvariantCultureIgnoreCase) AndAlso
Not fileName.EndsWith("_spec", StringComparison.InvariantCultureIgnoreCase)
End Function).
ToArray()这假设这些都是你所说的后缀。如果它们可能在名称中的任何位置,那么您可以相应地进行调整。
编辑: LINQ代码可以变得更简洁一些,如下所示:
Dim folderPath = "folder path here"
Dim filePaths = Directory.GetFiles("*.png").
Where(Function(filePath) {"_norm", "_spec"}.All(Function(suffix) Not Path.GetFileNameWithoutExtension(filePath).EndsWith(suffix, StringComparison.InvariantCultureIgnoreCase))).
ToArray()不过,对于那些不太熟悉LINQ的人来说,这一点可能不太清楚。
https://stackoverflow.com/questions/70693084
复制相似问题