How to filter files from FileSystem.GetFiles using LINQ?

Steven Young 261 Reputation points
2021-02-09T08:31:55.763+00:00

I want to get some files by some conditions, i can get the files by the file type, the code is below.
Dim wildcards As String() = {".mp3", ".ape"}
Dim ListFiles = FileIO.FileSystem.GetFiles("G:\Music", FileIO.SearchOption.SearchAllSubDirectories, wildcards)

Now I want to exclude the hidden, system properties and 0-byte files, how to add the LINQ express?
My .NET Framework version is 4.6, so I cannot use the Directory.EnumerateFiles method, thank you.

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,599 questions
{count} votes

Accepted answer
  1. Castorix31 81,941 Reputation points
    2021-02-09T09:18:40.667+00:00

    You can do something like this =>

           Dim ListFiles = FileIO.FileSystem.GetFiles("G:\Music", FileIO.SearchOption.SearchAllSubDirectories, wildcards).Where(Function(f) (FileLen(f) > 0 AndAlso (File.GetAttributes(f) And FileAttributes.Hidden) <> FileAttributes.Hidden AndAlso (File.GetAttributes(f) And FileAttributes.System) <> FileAttributes.System))
    

1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,196 Reputation points
    2021-02-09T20:32:43.277+00:00

    For dynamic

    Add your logic to determine the rules.

    Dim result As IEnumerable(Of String) = ListFiles.Where(Function(item) FileLen(item) > 0)
    result = result.Where(Function(f) (File.GetAttributes(f) And FileAttributes.Hidden) <> FileAttributes.Hidden)
    result = result.Where(Function(f) (File.GetAttributes(f) And FileAttributes.System) <> FileAttributes.System)