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?
LVL 1
yjtAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

RuchiCommented:
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
        End
    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.
        ResetSearch
        txtSearchSpec.SetFocus
        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"
    cmdSearch.SetFocus
    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
    Loop
    ' 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...
        Else
            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
DirDriverHandler:
    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
    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

DriveHandler:
    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
End Sub

Private Sub ResetSearch()
    ' Reinitialize before starting a new search.
    lstFoundFiles.Clear
    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


0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
prem_kumar_25Commented:
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 premkumar@dei.co.uk for the code...please specify the problem in the mail also..
0
VbmasterCommented:
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)
  Next

  (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
        Else
          av_Array(x) = MyName
        End If
      End If
    End If
    MyName = Dir$
  Loop
 
  If Recursive Then
    For a = 1 To MyDirNr
      If Not ListFiles(Path & MyDir(a) & "\", av_Array(), True, IncludePaths, Prefix, x, False) Then GoTo Errorhandler
    Next
  End If
  If StartDir Then ReDim Preserve av_Array(x)
  ListFiles = True
  Exit Function
 
Errorhandler:
  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.
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

RuchiCommented:
Did you get it or not? Please let me know how you are doing with your problem.
0
RuchiCommented:
VERSION 5.00
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
   End
   Begin VB.CommandButton btnSearch
      Caption         =   "Search"
      Height          =   255
      Left            =   3810
      TabIndex        =   3
      Top             =   75
      Width           =   885
   End
   Begin VB.TextBox txtFile
      Height          =   285
      Left            =   1200
      TabIndex        =   1
      Top             =   45
      Width           =   2520
   End
   Begin VB.ListBox List1
      Height          =   3180
      Left            =   30
      TabIndex        =   0
      Top             =   375
      Width           =   7455
   End
   Begin VB.Label Label2
      AutoSize        =   -1  'True
      BackStyle       =   0  'Transparent
      Caption         =   "Starting Point"
      Height          =   195
      Left            =   5430
      TabIndex        =   5
      Top             =   90
      Width           =   945
   End
   Begin VB.Label Label1
      AutoSize        =   -1  'True
      BackStyle       =   0  'Transparent
      Caption         =   "Search Pattern"
      Height          =   195
      Left            =   60
      TabIndex        =   2
      Top             =   90
      Width           =   1065
   End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
'Code by Chizl <chizl@karland.com>
'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 & "\"
       
        List1.Clear
       
        btnSearch.Caption = "Stop"
        GetListing txtStartAt, txtFile
       
        lStop = False
        btnSearch.Caption = "Search"
        Caption = "Done.."
    Else
        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)
        DoEvents
    Loop
   
    Caption = strDir$
   
    strDirName$ = Dir(strDir$, vbDirectory)
    Do While strDirName$ = "." 'Or strDirName$ = ".."
        If lStop Then GoTo ExitOut
        strDirName$ = Dir()
        DoEvents
    Loop
    ivarrCount = 1
   
    ReDim varrDir(ivarrCount) As Variant
    Do While strDirName$ <> ""
        If lStop Then GoTo ExitOut
        DoEvents
        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()
    Loop
   
    strFileName$ = Dir(strDir$ & strFile$)
   
    Do While strFileName$ <> ""
        If lStop Then GoTo ExitOut
        Caption = strDir$ & strFileName$
       
        DoEvents
        List1.AddItem strDir$ & strFileName$
        strFileName$ = Dir()
    Loop
   
    For i = 1 To UBound(varrDir)
        If lStop Then GoTo ExitOut
        DoEvents
        If varrDir(i) = "" Then Exit For
        GetListing strDir$ & CStr(varrDir(i)) & "\", strFile$
    Next
   
ExitOut:

End Sub
0
RuchiCommented:
Vjt: Where are you? Please say something so we could be of any help to you.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic Classic

From novice to tech pro — start learning today.