Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

File count routine in VB6 2

Status
Not open for further replies.

wmg

Technical User
Sep 13, 2001
216
NZ
Hello!

I am writing a program where I need to know the number of all files and folders contained underneath a user specified folder.

Short of recursing and couting, is there any way I can do this more efficiently (like maybe hooking into the Windows Folder properties dialog and grabbing the number of files and folders from there??).

Any ideas?
wmg
 
Might be worth checking if there is anything in the API for doing it, though I doubt it...
 
This code will iterate through all folders from a root and return the number of subfolders. It would be easy to modify it to return the file count as well. For large directories it can take a while, but at least the code is compact and easy to maintain.

Create a class called clsDirectory and paste the following function into it;

Public Function CountFolders(ByVal vsFolderName As String) As Long

Dim oDirectory As clsDirectory
Dim oFSO As FileSystemObject
Dim oFolder As Folder
Dim oSubFolder As Folder
Dim lFolderCount As Long

Set oFSO = New FileSystemObject
Set oFolder = oFSO.GetFolder(vsFolderName)
Set oDirectory = New clsDirectory

lFolderCount = oFolder.SubFolders.Count
For Each oSubFolder In oFolder.SubFolders
lFolderCount = lFolderCount + oDirectory.CountFolders (oSubFolder.Path)
Next

Set oSubFolder = Nothing
Set oFolder = Nothing
Set oFSO = Nothing

CountFolders = lFolderCount

End Function

You need to ensure you are referencing the Mircosoft Windows Scripting Library.
 
Great - thanks Chris - I'll give it a go. Any tips on what bits would be necessary to add to count files as well?

;-) (kinda newbie-ish..)
 
You don't need to add anything to the code. The function returns the number of files found... Troy Williams B.Eng.
fenris@hotmail.com

 
Excellent - thanks guys!
 
The function currently returns the folder count since it uses the 'subfolders.count' property. To get the file count as well you would need to also use the oFolder.Files.Count property and pass in a long value ByRef into the function to return the FileCount. Ideally you should rewrite the function to return True or False depending on errors, and pass in two ByRef variables for the folder and file counts.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top