question

StevenYoung-5410 avatar image
0 Votes"
StevenYoung-5410 asked StevenYoung-5410 commented

How to filter files from FileSystem.GetFiles using LINQ?

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.

dotnet-visual-basic
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.


I think that the required forms of EnumerateFiles are available in .NET Framework 4.6.

0 Votes 0 ·
Castorix31 avatar image
0 Votes"
Castorix31 answered StevenYoung-5410 commented

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
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

It's same with the code below.
Dim files = From f In ListFiles
Where FileLen(f) > 0
Where (File.GetAttributes(f) And FileAttributes.Hidden) <> FileAttributes.Hidden
Where (File.GetAttributes(f) And FileAttributes.System) <> FileAttributes.System
Select f

Another problem, how to add the where express dynamically? if the variable excludeHidden =true, then add the where express "(File.GetAttributes(f) And FileAttributes.Hidden) <> FileAttributes.Hidden", if the variable exclude0Byte =true, then add the where "FileLen(f) > 0", thank you.


0 Votes 0 ·
karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered StevenYoung-5410 commented

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)
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Yes, thank you.

0 Votes 0 ·