Recursive File Search Code

Below is the first function I’m publishing… It uses my favorite programing feature… recursion. Recursion is a tricky thing to do right. So many loops, so many variables, etc… This function searches for a file and all sub-directories of your root/starter directory. Source Code:

Public Function SearchForFile(ByVal strSourceDirectory As String, ByVal strSearchString As String) As String
  On Error Resume Next
  Dim ret As String = ""
  Dim dirInfo As New DirectoryInfo(strSourceDirectory)
  Dim fsInfo As FileSystemInfo

  For Each fsInfo In dirInfo.GetFileSystemInfos
    If TypeOf fsInfo Is FileInfo And _
      fsInfo.Name.IndexOfAny(strSearchString) > -1 Then
      'FOUND IT...
      If fsInfo.Name = strSearchString Then
        'return directory where file is located...
        ret = strSourceDirectory
        Exit For
      End If
      'recurrsively search this sub-folder...
      ret = SearchForFile(fsInfo.FullName, strSearchString)
      If ret <> "" Then Exit For
    End If

  If ret <> "" Then If Right(ret, 1) <> "\" Then ret = ret & "\"
  SearchForFile = ret
End Function


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s