HOWTO: Recursively Search Directories Using FileSystemObjectID: Q185601
|
The FileSystemObject class can be used to recursively search directories and find files. This article demonstrates the use of FileSystemObject to search for specific files.
The FileSystemObject class is found in the Scrrun.dll file, which can be
obtained by installing any one of the following packages:
Windows Script Host
Windows NT Option Pack
Microsoft Internet Information Server 3.0
Scripting 3.1 upgrade
Visual Studio 98
Visual Basic 6.0
Option Explicit
Dim fso As New FileSystemObject
Dim fld As Folder
Private Sub Command1_Click()
Dim nDirs As Integer, nFiles As Integer, lSize As Long
Dim sDir As String, sSrchString As String
sDir = InputBox("Please enter the directory to search", _
"FileSystemObjects example", "C:\")
sSrchString = InputBox("Please enter the file name to search", _
"FileSystemObjects example", "vb.ini")
MousePointer = vbHourglass
Label1.Caption = "Searching " & vbCrLf & UCase(sDir) & "..."
lSize = FindFile(sDir, sSrchString, nDirs, nFiles)
MousePointer = vbDefault
MsgBox Str(nFiles) & " files found in" & Str(nDirs) & _
" directories", vbInformation
MsgBox "Total Size = " & lSize & " bytes"
End Sub
Private Function FindFile(ByVal sFol As String, sFile As String, _
nDirs As Integer, nFiles As Integer) As Long
Dim tFld As Folder, tFil As File, FileName As String
Set fld = fso.GetFolder(sFol)
FileName = Dir(fso.BuildPath(fld.Path, sFile), vbNormal Or _
vbHidden Or vbSystem Or vbReadOnly)
While Len(FileName) <> 0
FindFile = FindFile + FileLen(fso.BuildPath(fld.Path, _
FileName))
nFiles = nFiles + 1
List1.AddItem fso.BuildPath(fld.Path, FileName) ' Load ListBox
FileName = Dir() ' Get next file
DoEvents
Wend
Label1 = "Searching " & vbCrLf & fld.Path & "..."
nDirs = nDirs + 1
If fld.SubFolders.Count > 0 Then
For Each tFld In fld.SubFolders
DoEvents
FindFile = FindFile + FindFile(tFld.Path, sFile, nDirs, _
nFiles)
Next
End If
End Function
For information on other methods you can use to find a specific file,
please see the following article in the Microsoft Knowledge Base:
Q185476 HOWTO: Search Directories to Find or List Files
Additional query words:
look subdirectory directory tree recursion recursive kbDSupport
kbDSD kbVBp500 File System Object filesystem kbVBp600
Keywords :
Version : WINDOWS:5.0,6.0
Platform : WINDOWS
Issue type : kbhowto
Last Reviewed: July 13, 1999