Searching file from whole hard disk

I would like to search for a particular file (eg. txt file) whether it is situated in any folders in the hard disk. I intended to use the Dir$ method but I need it to be a recursive function traversing all the subdirectories in the whole hard disk. Can anyone provide me the codes for this?
Who is Participating?
RuchiConnect With a Mentor Commented:
Take a look at the WinSeek sample with VB

C:\Program Files\DevStudio\VB\samples\Misc\FileCts\winseek.vbp

Or, you enter winseek in the index tab of the msdn library studio library. It brings you up the winseek.vbp.

This is from Winseek.vbp

Option Explicit
Dim SearchFlag As Integer   ' Used as flag for cancel and other operations.

Private Sub cmdExit_Click()
    If cmdExit.Caption = "E&xit" Then
    Else                    ' If user chose Cancel, just end Search.
        SearchFlag = False
    End If
End Sub

Private Sub cmdSearch_Click()
' Initialize for search, then perform recursive search.
Dim FirstPath As String, DirCount As Integer, NumFiles As Integer
Dim result As Integer
  ' Check what the user did last.
    If cmdSearch.Caption = "&Reset" Then  ' If just a reset, initialize and exit.
        Exit Sub
    End If

    ' Update dirList.Path if it is different from the currently
    ' selected directory, otherwise perform the search.
    If dirList.Path <> dirList.List(dirList.ListIndex) Then
        dirList.Path = dirList.List(dirList.ListIndex)
        Exit Sub         ' Exit so user can take a look before searching.
    End If

    ' Continue with the search.
    Picture2.Move 0, 0
    Picture1.Visible = False
    Picture2.Visible = True

    cmdExit.Caption = "Cancel"

    filList.Pattern = txtSearchSpec.Text
    FirstPath = dirList.Path
    DirCount = dirList.ListCount

    ' Start recursive direcory search.
    NumFiles = 0                       ' Reset found files indicator.
    result = DirDiver(FirstPath, DirCount, "")
    filList.Path = dirList.Path
    cmdSearch.Caption = "&Reset"
    cmdExit.Caption = "E&xit"
End Sub

Private Function DirDiver(NewPath As String, DirCount As Integer, BackUp As String) As Integer
'  Recursively search directories from NewPath down...
'  NewPath is searched on this recursion.
'  BackUp is origin of this recursion.
'  DirCount is number of subdirectories in this directory.
Static FirstErr As Integer
Dim DirsToPeek As Integer, AbandonSearch As Integer, ind As Integer
Dim OldPath As String, ThePath As String, entry As String
Dim retval As Integer
    SearchFlag = True           ' Set flag so the user can interrupt.
    DirDiver = False            ' Set to True if there is an error.
    retval = DoEvents()         ' Check for events (for instance, if the user chooses Cancel).
    If SearchFlag = False Then
        DirDiver = True
        Exit Function
    End If
    On Local Error GoTo DirDriverHandler
    DirsToPeek = dirList.ListCount                  ' How many directories below this?
    Do While DirsToPeek > 0 And SearchFlag = True
        OldPath = dirList.Path                      ' Save old path for next recursion.
        dirList.Path = NewPath
        If dirList.ListCount > 0 Then
            ' Get to the node bottom.
            dirList.Path = dirList.List(DirsToPeek - 1)
            AbandonSearch = DirDiver((dirList.Path), DirCount%, OldPath)
        End If
        ' Go up one level in directories.
        DirsToPeek = DirsToPeek - 1
        If AbandonSearch = True Then Exit Function
    ' Call function to enumerate files.
    If filList.ListCount Then
        If Len(dirList.Path) <= 3 Then             ' Check for 2 bytes/character
            ThePath = dirList.Path                  ' If at root level, leave as is...
            ThePath = dirList.Path + "\"            ' Otherwise put "\" before the filename.
        End If
        For ind = 0 To filList.ListCount - 1        ' Add conforming files in this directory to the list box.
            entry = ThePath + filList.List(ind)
            lstFoundFiles.AddItem entry
            lblCount.Caption = Str(Val(lblCount.Caption) + 1)
        Next ind
    End If
    If BackUp <> "" Then        ' If there is a superior directory, move it.
        dirList.Path = BackUp
    End If
    Exit Function
    If Err = 7 Then             ' If Out of Memory error occurs, assume the list box just got full.
        DirDiver = True         ' Create Msg and set return value AbandonSearch.
        MsgBox "You've filled the list box. Abandoning search..."
        Exit Function           ' Note that the exit procedure resets Err to 0.
    Else                        ' Otherwise display error message and quit.
        MsgBox Error
    End If
End Function

Private Sub DirList_Change()
    ' Update the file list box to synchronize with the directory list box.
    filList.Path = dirList.Path
End Sub

Private Sub DirList_LostFocus()
    dirList.Path = dirList.List(dirList.ListIndex)
End Sub

Private Sub DrvList_Change()
    On Error GoTo DriveHandler
    dirList.Path = drvList.Drive
    Exit Sub

    drvList.Drive = dirList.Path
    Exit Sub
End Sub

Private Sub Form_Load()
    Picture2.Move 0, 0
    Picture2.Width = WinSeek.ScaleWidth
    Picture2.BackColor = WinSeek.BackColor
    lblCount.BackColor = WinSeek.BackColor
    lblCriteria.BackColor = WinSeek.BackColor
    lblfound.BackColor = WinSeek.BackColor
    Picture1.Move 0, 0
    Picture1.Width = WinSeek.ScaleWidth
    Picture1.BackColor = WinSeek.BackColor
End Sub

Private Sub Form_Unload(Cancel As Integer)
End Sub

Private Sub ResetSearch()
    ' Reinitialize before starting a new search.
    lblCount.Caption = 0
    SearchFlag = False                  ' Flag indicating search in progress.
    Picture2.Visible = False
    cmdSearch.Caption = "&Search"
    cmdExit.Caption = "E&xit"
    Picture1.Visible = True
    dirList.Path = CurDir: drvList.Drive = dirList.Path ' Reset the path.
End Sub

Private Sub txtSearchSpec_Change()
    ' Update file list box if user changes pattern.
    filList.Pattern = txtSearchSpec.Text
End Sub

Private Sub txtSearchSpec_GotFocus()
    txtSearchSpec.SelStart = 0          ' Highlight the current entry.
    txtSearchSpec.SelLength = Len(txtSearchSpec.Text)
End Sub

Dear Yjt

     This can be done by the Dir$ method itself first what u have to do is search the root . then create an array and store the directories into that array and then go to each of these directories and proceed the same way by searching the directory and then storing the directories into an array and carry on , hope this will solve ur problem ... if this is not clear for u, and u want a code for this i can do this u can feel free to email me at for the code...please specify the problem in the mail also..
Here's a function you can use..

Use it with code like

  Dim FilesFound() As String

  Call ListFiles("C:\", FilesFound, True, True, "*.txt")
  For a = 1 to Ubound(FilesFound)
    Debug.Print FilesFound(a)

  (The two last parameters are not to be used.. unless you know what you are doing..)

Function ListFiles(ByVal Path As String, ByRef av_Array() As String, Recursive As Boolean, Optional IncludePaths As Boolean = True, Optional Prefix As String = "*.*", Optional ByRef x As Long = 0, Optional StartDir As Boolean = True)

  Dim MyName  As String
  Dim MyDir() As String
  Dim MyDirNr As Integer
  Dim a       As Integer
  MyDirNr = 0
  If StartDir Then
    x = 0
    Path = IIf(Right$(Path, 1) = "\", Path, Path & "\")
    Prefix = UCase$(Prefix)
  End If
  On Error GoTo Errorhandler
  MyName = Dir$(Path & "*.*", vbDirectory + vbArchive + vbHidden + vbReadOnly + vbSystem)
  Do While (Len(MyName) > 0)
    If (MyName <> ".") And (MyName <> "..") Then
      If (GetAttr(Path & MyName) And vbDirectory) = vbDirectory Then
        ReDim Preserve MyDir(MyDirNr + 1)
        MyDirNr = MyDirNr + 1
        MyDir(MyDirNr) = MyName
      ElseIf (UCase$(MyName) Like Prefix) Then
        If (x Mod 10 = 0) Then ReDim Preserve av_Array(x + 10)
        x = x + 1
        If IncludePaths Then
          av_Array(x) = Path & MyName
          av_Array(x) = MyName
        End If
      End If
    End If
    MyName = Dir$
  If Recursive Then
    For a = 1 To MyDirNr
      If Not ListFiles(Path & MyDir(a) & "\", av_Array(), True, IncludePaths, Prefix, x, False) Then GoTo Errorhandler
  End If
  If StartDir Then ReDim Preserve av_Array(x)
  ListFiles = True
  Exit Function
  ListFiles = False

End Function

I think it's kinda easy to use this function, but if you have any problems leave a comment and I'll help ya.

And ya, the function returns TRUE if it was successful, and FALSE if any errors was encountered.
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Did you get it or not? Please let me know how you are doing with your problem.
Begin VB.Form Form1
   BorderStyle     =   1  'Fixed Single
   Caption         =   "Personal File Search"
   ClientHeight    =   3600
   ClientLeft      =   45
   ClientTop       =   330
   ClientWidth     =   7515
   LinkTopic       =   "Form1"
   LockControls    =   -1  'True
   MaxButton       =   0   'False
   ScaleHeight     =   3600
   ScaleWidth      =   7515
   StartUpPosition =   3  'Windows Default
   Begin VB.TextBox txtStartAt
      Height          =   285
      Left            =   6450
      TabIndex        =   4
      Text            =   "C:\"
      Top             =   60
      Width           =   1035
   Begin VB.CommandButton btnSearch
      Caption         =   "Search"
      Height          =   255
      Left            =   3810
      TabIndex        =   3
      Top             =   75
      Width           =   885
   Begin VB.TextBox txtFile
      Height          =   285
      Left            =   1200
      TabIndex        =   1
      Top             =   45
      Width           =   2520
   Begin VB.ListBox List1
      Height          =   3180
      Left            =   30
      TabIndex        =   0
      Top             =   375
      Width           =   7455
   Begin VB.Label Label2
      AutoSize        =   -1  'True
      BackStyle       =   0  'Transparent
      Caption         =   "Starting Point"
      Height          =   195
      Left            =   5430
      TabIndex        =   5
      Top             =   90
      Width           =   945
   Begin VB.Label Label1
      AutoSize        =   -1  'True
      BackStyle       =   0  'Transparent
      Caption         =   "Search Pattern"
      Height          =   195
      Left            =   60
      TabIndex        =   2
      Top             =   90
      Width           =   1065
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
'Code by Chizl <>
'15 minute code time.
'Karland International
'Copyrighted (c) 1999
'Public Domain as long as this header is attached.

'This does not search Hidden Directories!!!!

Dim lStop As Boolean

Private Sub btnSearch_Click()
    If btnSearch.Caption = "Search" Then
        If Right(txtStartAt, 1) <> "\" Then txtStartAt = txtStartAt & "\"
        btnSearch.Caption = "Stop"
        GetListing txtStartAt, txtFile
        lStop = False
        btnSearch.Caption = "Search"
        Caption = "Done.."
        lStop = True
        btnSearch.Caption = "Search"
    End If
End Sub

Private Sub GetListing(strDir$, strFile$)
    Dim varrDir As Variant
    Dim ivarrCount

    Dim strFileName$
    Dim strDirName$
    Do While Right(strDir$, 2) = "\\"
        If lStop Then GoTo ExitOut
        strDir$ = Mid(strDir$, 1, Len(strDir$) - 1)
    Caption = strDir$
    strDirName$ = Dir(strDir$, vbDirectory)
    Do While strDirName$ = "." 'Or strDirName$ = ".."
        If lStop Then GoTo ExitOut
        strDirName$ = Dir()
    ivarrCount = 1
    ReDim varrDir(ivarrCount) As Variant
    Do While strDirName$ <> ""
        If lStop Then GoTo ExitOut
        If LCase(strDirName$) = LCase(strFile$) Then
            List1.AddItem strDir$ & strDirName$
        End If
        If InStr(strDirName$, ".") = 0 Then
            varrDir(ivarrCount) = strDirName$
            ivarrCount = UBound(varrDir) + 1
            ReDim Preserve varrDir(ivarrCount) As Variant
        End If
        strDirName$ = Dir()
    strFileName$ = Dir(strDir$ & strFile$)
    Do While strFileName$ <> ""
        If lStop Then GoTo ExitOut
        Caption = strDir$ & strFileName$
        List1.AddItem strDir$ & strFileName$
        strFileName$ = Dir()
    For i = 1 To UBound(varrDir)
        If lStop Then GoTo ExitOut
        If varrDir(i) = "" Then Exit For
        GetListing strDir$ & CStr(varrDir(i)) & "\", strFile$

End Sub
Vjt: Where are you? Please say something so we could be of any help to you.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.