我正在使用以下代码在我的计算机中搜索带有certian扩展名的文件。我目前正在搜索.eml文件。此代码列出了找到的所有文件。 我需要在列表框中输入10个最新文件的路径。我该怎么做?感谢
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
答案 0 :(得分:1)
不是将找到的文件添加到列表框目录,而是首先将找到的FileInfo添加到列表中。找到所有文件后,使用linq查询查找最近的10个文件并将其添加到列表中。
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