我正在制作一个程序,在您的驱动器中搜索可执行文件。
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim di As New DirectoryInfo("C:\")
Dim files() As FileInfo
Dim a As Integer
Do While a = 0
Try
files = di.GetFiles("FileName.exe", SearchOption.AllDirectories)
Catch ex As UnauthorizedAccessException
End Try
If Not files Is Nothing Then
a = 1
End If
Loop
txt_Location.Text = files(0).FullName
End Sub
一旦遇到第一个UnauthorizedAccessException,它就会陷入无限循环。如何跳过产生异常的文件?
编辑: 这就是我现在所拥有的:
Public Sub DirSearch(ByVal sDir As String)
Dim dir As String
Try
For Each dir In Directory.GetDirectories(sDir)
For Each file In Directory.GetFiles(dir, "Filename.exe")
ComboBox1.Items.Add(file)
Next
DirSearch(dir)
Next
Catch ex As Exception
Debug.WriteLine(ex.Message)
End Try
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
DirSearch("C:\")
End Sub
答案 0 :(得分:4)
这里需要递归来处理每个文件夹。
编辑:根据OP的要求,举个例子:
Public Sub DirSearch(ByVal sDir As String)
Try
For Each dir as String In Directory.GetDirectories(sDir)
For Each file In Directory.GetFiles(dir, "yourfilename.exe")
lstFilesFound.Items.Add(file)
Next
DirSearch(dir)
Next
Catch ex As Exception
Debug.WriteLine(ex.Message)
End Try
End Sub
另请查看以下答案:
另请注意,如果您有足够的访问权限,则可以将代码简化为:
Dim di as New DirectoryInfo()
Dim files = di.GetFiles("iexplore.exe", SearchOption.AllDirectories) 'already returns all files at once
最后但并非最不重要:
避免无限循环。就像在你的例子中一样,它们可能导致代码损坏,因为有些情况并不像你预期的那样。想象一下,您的代码已经在您的PC上运行,并且您将此软件部署到客户 - 可怕的场景。 ; - )