我一直想知道从vb.net的目录和子目录中获取文件的最快,最有效的方法是什么? 香港专业教育学院尝试了这些:
方法1
Private Sub getallfiles(filelocation As String)
Try
For Each item As String In My.Computer.FileSystem.GetFiles(filelocation)
Me.Invoke(Sub() ListBox1.Items.Add(item))
Me.Invoke(Sub() ListBox1.SelectedIndex = ListBox1.Items.Count - 1)
Next
For Each folder As String In My.Computer.FileSystem.GetDirectories(filelocation)
Me.Invoke(Sub() getallfiles(folder))
Next
Catch ex As Exception
End Try
End Sub
方法2
Dim FilesFromDir() As String = Directory.GetFiles("C:\Users\user\Documents\TextNotes", "*.txt", SearchOption.AllDirectories)
ListBox3.Items.AddRange(FilesFromDir)
答案 0 :(得分:1)
将项目添加到列表中,而不是在每次迭代时都单击ListBox。然后调用.BeginUpdate和.EndUpdate,这样列表框只需要重绘一次。
Private Sub getallfiles(filelocation As String)
Dim lstFiles As New List(Of String)
Try
For Each item As String In My.Computer.FileSystem.GetFiles(filelocation)
lstFiles.Add(item)
Next
For Each folder As String In My.Computer.FileSystem.GetDirectories(filelocation)
getallfiles(folder)
Next
Catch ex As Exception
End Try
Me.Invoke(Sub()
ListBox1.BeginUpdate()
ListBox1.Items.AddRange(lstFiles.ToArray)
ListBox1.EndUpdate()
End Sub)
End Sub