|
-
May 1st, 2023, 12:17 PM
#1
Thread Starter
Frenzied Member
[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)
Last edited by nbrege; May 1st, 2023 at 12:23 PM.
-
May 1st, 2023, 12:51 PM
#2
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
-
May 1st, 2023, 01:31 PM
#3
Thread Starter
Frenzied Member
Re: Querying a list of FileInfo for a filename
 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.
-
May 1st, 2023, 05:20 PM
#4
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
-
May 2nd, 2023, 07:51 AM
#5
Thread Starter
Frenzied Member
Re: Querying a list of FileInfo for a filename
Niya, thank you, that worked perfectly...
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|