0

I am making a program that searches your drive for an executable.

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

As soon as it hits the first UnauthorizedAccessException, it gets stuck in an infinite loop. How do I skip over the files that produce the exception?

EDIT: This is what I have now:

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
Spartin503
  • 47
  • 3
  • 9
  • possible duplicate of [Looping through all directory's on the hard drive](http://stackoverflow.com/questions/3864530/looping-through-all-directorys-on-the-hard-drive) – Ken White Aug 02 '13 at 17:24

1 Answers1

4

You need recursion here which handles each folder.

EDIT: As requested by the OP, a little example:

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

Also take a look at the following answers:


Also note, if you have enough access rights, you could simplify your code to this:

Dim di as New DirectoryInfo()
Dim files = di.GetFiles("iexplore.exe", SearchOption.AllDirectories) 'already returns all files at once

And at last but not least:

Avoid having infinite loops. Like in your example, they can lead to broken code just because some circumstances aren't like you've expected them to be. Imagine your code has run on your PC and you deployed this software to a customer - horrible scenario. ;-)

Community
  • 1
  • 1
Fabian Bigler
  • 10,403
  • 6
  • 47
  • 70