[RESOLVED] Querying a list of FileInfo for a filename
I am using the code below to get a list of files from multiple folder paths. Now I want to query that list to see if a specified file name exists. I don't want to loop through the list one file at a time, but rather use something like LINQ, but I'm not sure how to do it. I'm hoping someone can help me out. Thanks...
Code:
Dim allFiles As New List(Of IO.FileInfo)
Dim files As IO.FileInfo()
files = New IO.DirectoryInfo(folderPath1).GetFiles("*")
allFiles.AddRange(files)
files = New IO.DirectoryInfo(folderPath2).GetFiles("*")
allFiles.AddRange(files)
files = New IO.DirectoryInfo(folderPath3).GetFiles("*", IO.SearchOption.AllDirectories)
allFiles.AddRange(files)
Re: Querying a list of FileInfo for a filename
Can we assume that it does not matter what path the file name is in, or if it is in more than one path?
Possibly useful links:
https://learn.microsoft.com/en-us/do...s?view=net-8.0
https://www.codeproject.com/Question...ist-using-linq
Re: Querying a list of FileInfo for a filename
Quote:
Originally Posted by
jdc2000
Can we assume that it does not matter what path the file name is in, or if it is in more than one path?
That is correct, path doesn't matter, and there should only be 1 copy of a file.
Re: Querying a list of FileInfo for a filename
You want LINQ's FirstOrDefault for this:-
Code:
'Name of file to find
Dim findFile As String = "target.txt"
'The first match found would be assigned to this variable. Nothing is assigned
'if no matches were found.
Dim foundFile As FileInfo = allfiles.FirstOrDefault(Function(f) f.Name.ToLower = findFile)
'If a match was not found then 'foundFile' would be Nothing...
If foundFile IsNot Nothing Then
Debug.WriteLine($"{foundFile.FullName}, Size = {foundFile.Length.ToString}")
End If
Re: Querying a list of FileInfo for a filename
Niya, thank you, that worked perfectly...