I want to search specific folder for a png files, which are not consist a given pattern, and add them to the listbox. So I want to find pngs which don't have _norm or _spec in their names. Paterrn could be in uppercase or lowercase.
Files in folder:
- a.png
- a_norm.png
- a_spec.png
- a_Spec.png
- a_Norm.png
wished result in the listbox:
a.png
CodePudding user response:
With GetFiles there's no option to exclude files only a pattern to include files, so one must first get all files that fit the pattern and then exclude the unwanted ones.
Following method excludes files containing one of the provided strings in exclusions and ignores the casing:
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
Usage:
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
CodePudding user response:
You can't do it using GetFiles, which can only filter based on matching a mask, not not matching it. You need to get all the files and then discard the ones you don't want with appropriate String comparisons. That could look like this:
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()
This assumes that those are suffixes you're talking about. If they could be anywhere in the name then you can adjust accordingly.
