0

我正在制作一个程序来搜索您的驱动器以查找可执行文件。

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
4

1 回答 1

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 上运行,并且您将该软件部署到了客户——这很糟糕。;-)

于 2013-08-02T17:33:17.000 回答