Reputation: 4997
i am using following code to search my computer for files with certian extensions. I currenty searching for .eml files. This code lists all files found. I need to enter 10 most current files' path to my list box. How can I do it? Thanks
Dim DriveLetter As String = "c:\" '"
Dim Ext As String = ".eml"
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.SearchPath(DriveLetter)
End Sub
Sub SearchPath(ByVal Path As String)
Dim DirParent As New IO.DirectoryInfo(Path)
''# Me.AddResults("Searching: " & DirParent.FullName)
Dim ListFiles() As IO.FileInfo
Try
ListFiles = DirParent.GetFiles("*" & Ext)
For Each SingleFile In ListFiles
Me.AddResults("Found: " & SingleFile.FullName)
Application.DoEvents()
Next
Catch ex As Exception
''# Me.AddResults("GET FILES ERROR: " & ex.Message)
End Try
Try
Dim DirChildren() As IO.DirectoryInfo = DirParent.GetDirectories
For Each DirEnum In DirChildren
SearchPath(DirEnum.FullName)
Next
Catch ex As Exception
''# Me.AddResults("GET DIRS ERROR: " & ex.Message)
End Try
End Sub
Sub AddResults(ByVal ResultString As String)
lstFiles.Items.Add(ResultString)
Application.DoEvents()
End Sub
Upvotes: 0
Views: 2915
Reputation: 4932
Instead of adding the found files to list box directory add the found FileInfo to a list first. When all the files have been found use a linq query to find the 10 most recent files and add that to the list.
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs
) Handles button1.Click
' Note C:\\ is required to stackoverflow.com formatting '
Dim foundFiles = SearchPath("C:\\", ".eml")
Dim recentFiles = From file In foundFiles
Order By File.LastWriteTime Descending
Take 10
lstFiles.Items.Clear()
For Each file In recentFiles
lstFiles.Items.Add(file.FullName)
Next
End Sub
Function SearchPath(ByVal path As String,
ByVal ext As String
) As List(Of FileInfo)
Dim dirParent = New IO.DirectoryInfo(path)
Dim foundFiles = New List(Of FileInfo)
foundFiles.AddRange(dirParent.GetFiles("*" & ext))
For Each directory In dirParent.GetDirectories()
Try
foundFiles.AddRange(SearchPath(directory.FullName, ext))
Catch ex As System.UnauthorizedAccessException
' Ignore these exceptions. '
End Try
Next
Return foundFiles
End Function
Upvotes: 1