Visual Basic Code of the Week (COTW)
http://www.codeoftheweek.com
Issue #44
Online Version at http://www.codeoftheweek.com/membersonly/bi/0044.html (paid subscribers only)
All content and source code is Copyright (c) 1998 by C&D Programming Corp. No part of this issue can be reprinted or distributed in any manner without express written permission of C&D Programming Corp.

Our sponsor for this issue - http://www.quickreports.com

Over 3000 Pages Of Reports, Books, Guides, Money-Making Ideas, Opportunities, Forms and Much More! With full text access to the reports, you can edit, format and print them as you wish. Use them to create advertisements, newsletters, press releases and booklets. You can also sell them as printed reports, or as report software by copying them onto floppy disks. Market them individually, or in sets. You can even market the CD-ROM!

Whether you are just getting started, or already operate a small or home-based business, the Report Broker 2000 CD-ROM is the perfect way to tap into the high-profit information publishing industry!

For complete details or to place your order, please visit http://www.quickreports.com


Notes about this ezine

If you are not a paid subscriber, you must have signed up for our free trial at http://www.codeoftheweek.com. Our ezine is not an unsolicited message (in other words a spam email). Keep in mind that if you signed up for our free trial you can still receive a total of four issues at no cost to you. After you receive the four issues you will be notified about continuing your subscription.

If you do not wish to continue to receive this ezine, please email us at cancel@codeoftheweek.com

Requirements for this Issue

The source code in this issue is designed for Visual Basic 5.0 32-bit and above. It will work in VB 4.0 with small changes to the error handlers. It is geared towards the intermediate to advanced programmer.

If you have any questions about this issue, please email us at questions@codeoftheweek.com

In this Issue

This issue introduces a class for searching a directory and all its subdirectories for a particular file mask. This is similiar to the way the Find Files feature works in Windows 95.

cFindFiles

There is one property and one method that are critical to using the cFindFiles class successfully.

Public Property Set StatusBox(txtStatus As Object)
Public Function FindFiles(sPath As String, sSearchMask As String) As Collection

Parameters

Returns

FindFiles will return a collection of matching filenames based on the sPath and sSearchMask. If any errors occur they will be raised to the caller.

Notes

If you want to additional criteria, we have added comments to an area in FindFiles where you can insert them. Some examples might be to search for files over a certain size or older than a certain number of days. This is a feature that one of our subscribers specifically asked for. If you have any source code you are interested in seeing in Code of the Week, email us at issueideas@codeoftheweek.com

Sample Usage

This example shows how to use the cFindFiles class. It assumes you have a form with a label called lblStatus, a list box called lstFiles and two text boxes called txtPath and txtMask. txtPath will contain the path to start the search from (such as F:\ or C:\WINDOWS) and txtMask will be the file type to search for, such as *.txt or *.*

    Dim cFind As New cFindFiles
    Dim Files As Collection
    Dim sFile As Variant

    Set cFind.StatusBox = lblStatus   ' This is where the search path will be shown while searching
    Set Files = cFind.FindFiles(txtPath, txtMask, True)
    For Each sFile In Files
        lstFiles.AddItem sFile
    Next

Source Code

Just paste this source code into a class module called cFindFiles and include it in your project.

'----------------------------------------------------------------------
'
'   Class Name:     cFindFiles
'   Written By:     C&D Programming Corp.
'   Create Date:    2/98
'   Copyright:      Copyright 1998 by C&D Programming Corp.  Source
'                   code may not be reproduced except for use in a
'                   compiled executable.  All rights reserved.  If
'                   you would like to reprint any or all of this
'                   code please email us at info@codeoftheweek.com
'----------------------------------------------------------------------
Option Explicit

Private colFiles As New Collection      ' to hold matching files
Private colDirs As New Collection       ' to hold matching directories
Private mtxtStatus As Object             ' place to show what directory we are up to.
                                        ' should normally be a text box or a label

Public Property Set StatusBox(txtStatus As Object)
    Set mtxtStatus = txtStatus
End Property

Public Property Get StatusBox() As Object
    Set StatusBox = mtxtStatus
End Property

Public Sub GatherDirectories(sPath As String)
    Dim sFilename As String   ' Walking sFilename variable.
    Dim sDirName As Variant    ' SubDirectory Name.
    Dim bFoundDir As Boolean  ' Found a directory on this pass
    Dim colTempDirs As New Collection    ' temporary collection for gathering directories

    On Error GoTo ErrHandler

    ' Make sure there is a backslash on the path
    If Right(sPath, 1) <> "\" Then sPath = sPath & "\"

    bFoundDir = False
    sDirName = Dir(sPath, vbDirectory Or vbHidden)  ' Even if hidden.
    Do While Len(sDirName) > 0

        ' Ignore the current and parent directories.
        If (sDirName <> ".") And (sDirName <> "..") Then

            ' Check for directory with bitwise comparison.
            If GetAttr(sPath & sDirName) And vbDirectory Then

                If Not StatusBox Is Nothing Then
                    StatusBox = sPath & sDirName
                    StatusBox.Refresh
                End If

                ' remember this directory for later search of the file name
                colDirs.Add sPath & sDirName

                ' remember the current directory for later so we can search it
                ' for more subdirectories
                colTempDirs.Add sDirName
                bFoundDir = True

            End If

        End If

        sDirName = Dir()  ' Get next subdirectory.
    Loop

    ' If there were sub-directories found above...
    If bFoundDir Then
       ' Recursively walk into them
        For Each sDirName In colTempDirs
            GatherDirectories sPath & sDirName & "\"
        Next
    End If

    Exit Sub

ErrHandler:
    Err.Raise Err.Number, Err.Source, Err.Description
End Sub

Public Function FindFiles(sPath As String, sSearchMask As String) As Collection
    Dim sFilename As String   ' Walking sFilename variable.
    Dim sDirName As Variant   ' SubDirectory Name.
    Dim lDirs As Long

    On Error GoTo ErrHandler

    ClearDirCollection          ' make sure the directory collection is erased

    GatherDirectories sPath     ' get list of valid directories below sPath

    For lDirs = colDirs.Count To 1 Step -1
        sDirName = colDirs.Item(lDirs)
        ' Search through directories and sum file sizes.
        sFilename = Dir(sDirName & "\" & sSearchMask, _
                    vbNormal Or vbHidden Or vbSystem Or vbReadOnly)
        If sFilename = "" Then
            colDirs.Remove lDirs    ' remove this directory since it does not contain
                                    ' any matching files
        Else
            Debug.Print sDirName
            '
            ' loop through matching files in this directory.
            '
            While Len(sFilename) <> 0
                '
                ' Add any file checking here to filter files further, such as date/time
                ' checking or size checking.
                ' In future issues we will show a way to add callback features to this
                ' routine so that you will not ever need to modify this code.
                '

                ' Add to file collection here
                colFiles.Add sDirName & "\" & sFilename

                sFilename = Dir()  ' Get next file.
            Wend
        End If

    Next

    ' return collection of files
    Set FindFiles = colFiles

    Exit Function

ErrHandler:
    Err.Raise Err.Number, Err.Source, Err.Description
    Resume
End Function

Private Sub ClearDirCollection()
    Dim lIndex As Long  ' remove loop index

    ' make directory collection empty
    If colDirs.Count > 0 Then
        For lIndex = colDirs.Count - 1 To 0 Step -1
            colDirs.Remove lIndex
        Next
    End If
    Set colDirs = Nothing
End Sub

Private Sub Class_Initialize()
    Set mtxtStatus = Nothing
End Sub

This document is available on the web

Paid subscribers can view this issue in HTML format. There is no additional source or information in the HTML formatted document. It just looks a little better since we have included some HTML formatting. Just point your browser to link at the top of this document.

Summary

That concludes this issue of COTW. We hope you find the source code useful in your development.

The below describes the ways you can supply us some feedback about COTW. We would like to see our members help mold COTW into the best Visual Basic source code resource available. But to do that we need your feedback about what you like and what you do not like about COTW.

Advertising

If you are interested in advertising in COTW please email us at sponsor@codeoftheweek.com Our rates are VERY reasonable, actually they are almost FREE. We reach over three thousand Visual Basic developers each week.

How to tell us what you think

If you have any suggestions for topics you would like to see covered or questions about this issue, please email them to info@codeoftheweek.com or use online feedback form at http://www.codeoftheweek.com/feedback.html.

If you have any source code you would like to submit for possible inclusion in COTW, please fill out our online submission form at http://www.codeoftheweek.com/submission.html.

Contact Information

C&D Programming Corp.
PO Box 20128
Floral Park, NY 11002-0128
Phone or Fax: (212) 504-7945
Email: info@codeoftheweek.com
Web: http://www.codeoftheweek.com

Subscription Update

Thank you for trying Code of the Week for Visual Basic.

Your free trial expires after you receive your fourth issue. If you want to continue to receive Code of the Week you can get 52 issues of COTW for only $19.95. This is a full year of Visual Basic source code and information to help with all your development. So don't wait, subscribe now! The quickest way to subscribe is to jump to our online order form at http://www.codeoftheweek.com/order.html