Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
TitleSearch for files matching a pattern by using the Dir commmand
Keywordsfind files, pattern, Dir
CategoriesFiles and Directories
 
Subroutine ListFiles uses the Dir command to look for files in the start directory. It then makes a list of subdirectories and recursively calls itself to search them.

Note that the Dir command is not safe for recursion so you cannot search a subdirectory until you have finished searching the current directory.

 
' List all files below the directory that
' match the pattern.
Private Sub ListFiles(ByVal start_dir As String, ByVal _
    pattern As String, ByVal lst As ListBox)
Dim dir_names() As String
Dim num_dirs As Integer
Dim i As Integer
Dim fname As String
Dim attr As Integer

    ' Protects against such things as
    ' GetAttr("C:\pagefile.sys").
    On Error Resume Next
    
    ' Get the matching files in this directory.
    fname = Dir(start_dir & "\" & pattern, vbNormal)
    Do While fname <> ""
        lst.AddItem start_dir & "\" & fname
        fname = Dir()
    Loop

    ' Get the list of subdirectories.
    fname = Dir(start_dir & "\*.*", vbDirectory)
    Do While fname <> ""
        ' Skip this dir and its parent.
        attr = 0    ' In case there's an error.
        attr = GetAttr(start_dir & "\" & fname)
        If fname <> "." And fname <> ".." And _
            (attr And vbDirectory) <> 0 _
        Then
            num_dirs = num_dirs + 1
            ReDim Preserve dir_names(1 To num_dirs)
            dir_names(num_dirs) = fname
        End If
        fname = Dir()
    Loop

    ' Search the other directories.
    For i = 1 To num_dirs
        ListFiles start_dir & "\" & dir_names(i), pattern, _
            lst
    Next i
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated