Solved

explore directory using fso

Posted on 2001-07-30
5
180 Views
Last Modified: 2012-08-14
Hi All,
By selecting one directory and clicking start button I need to be able to read the names of all the folders in the directory tree recursive without any more interruption with user. File System Object must be used. Code example would be greatly appreciated.

Thanks.
0
Comment
Question by:andr
  • 2
  • 2
5 Comments
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
Something like this:

Private Sub GetPortefeuilles(ByVal pstrModele As String)
Dim intPos As Integer
Dim objFile As File
Dim objFolderChild As Folder
Dim objFolderSource As Folder
Dim objFSO As FileSystemObject
   
    Set objFSO = New FileSystemObject
    strPath = objFSO.GetFile(gstrFileName).ParentFolder.ParentFolder.Path
    Set objFolderSource = objFSO.GetFolder(strPath & strSubFolder)
   
    For Each objFolderChild In objFolderSource.SubFolders
        'Boucle pour ramasser tous les fichiers portefeuilles
        For Each objFile In objFolderChild.Files
                    If objFile.Name Like "*.csv" Then
                        msgbox objFile.Path & objFile.Name
                    End If
        Next objFile
    Next objFolderChild
End Sub
0
 
LVL 43

Expert Comment

by:TimCottee
Comment Utility
andr here is an example, this is a little over the top perhaps but it returns all files and folders from a specified starting point, this can be chosen in a number of ways.

Private Sub Command1_Click()
    Dim colFiles As New Collection
    Set colFiles = GetFileList("UPF\Personal", "*.*", , True)
    MsgBox colFiles.Count
End Sub

Public Function GetFileList(strFolderPath As String, Optional strExtension As String = "*.*", Optional enuAttributes As FileAttribute = 0, Optional ByVal blnSearchSubFolders As Boolean = False, Optional ByRef colExisting As Collection) As Collection
    'Make sure a reference has been set to Microsoft Scripting Runtime
    'scrrun.dll before attempting to compile this code.
    '(c) TechRepublic, 2001 all rights reserved
    'The Windows Script Host Model must also be installed and registered to use the profile specific
    'switches in the folderpath argument: WSHOM.OCX
    'The folder path parameter may be one of the following:
    '1) A complete folder path either in Drive:\Folder\subfolder or in UNC e.g, \\ServerName\ShareName\Folder\SubFolder
    '2) A special folder
    '   a) WindowsFolder            :WindowsFolder
    '   b) Windows System Folder    :SystemFolder
    '   c) Temporary Files Folder   :TempFolder
    '3) A profile specific path to a system folder this is identified by prefixing with "UPF\" and may be one of the following
    '   a) Administrative Tools
    '   b) AppData
    '   c) Cache
    '   d) Cookies
    '   e) Desktop
    '   f) Favourites
    '   g) History
    '   h) Local AppData
    '   i) My Pictures
    '   j) NetHood
    '   k) Personal AKA My Documents
    '   l) PrintHood
    '   m) Programs
    '   n) Recent
    '   p) SendTo
    '   q) Start Menu
    '   r) Startup
    '   There may be additional options under Windows 9x, Windows 2000 or Windows XP.
    'The extension parameter may be specified either as "txt" to return all files matching this extension
    'or with a wildcarded filename, the wildcard characters "*" and "?" may be used both in the
    'filename and extension parts, following the standard windows rules for these things
    'The blnSearchSubFolders parameter may be used to search only the specified folder (False) or all subfolders (True)
    'The colExisting parameter may be passed an existing collection, this can be used to create a collection first
    'and then run consecutive searches on different criteria and return the result in one collection
    'this is effectively what is achieved by the recursion into this routine when searching
    'all subfolders from the given starting point.
    Dim fs As Scripting.FileSystemObject
    Dim fldr As Scripting.Folder
    Dim subfldr As Scripting.Folder
    Dim f As Scripting.File
    Dim strProfileRoot As String
    'Get the user's special folder root reference
    strProfileRoot = Environ("UserProfile")
    'Get reference to file system
    Set fs = New FileSystemObject
    'Check for a special folder
    Select Case UCase(strFolderPath)
    Case "WINDOWSFOLDER"
        strFolderPath = fs.GetSpecialFolder(0)
    Case "SYSTEMFOLDER"
        strFolderPath = fs.GetSpecialFolder(1)
    Case "TEMPFOLDER"
        strFolderPath = fs.GetSpecialFolder(2)
    End Select
    'Check for a profile specific folder
    If Left$(UCase(strFolderPath), 4) = "UPF\" Then
        'Get rid of the UPF\ part
        strFolderPath = Right$(strFolderPath, Len(strFolderPath) - 4)
        'Get the real location of this folder from the registry
        strFolderPath = strProfileRoot & GetActualPathFromRegistry(strFolderPath)
    End If
    'Check that the folder exists
    If fs.FolderExists(strFolderPath) Then
        'Create a new collection to store the
        'file objects in
        If colExisting Is Nothing Then
            Set GetFileList = New Collection
        Else
            Set GetFileList = colExisting
        End If
        'Get a pointer to the folder
        Set fldr = fs.GetFolder(strFolderPath)
        'Should we search this folder only or include sub folders
        If blnSearchSubFolders Then
            For Each subfldr In fldr.SubFolders
                GetFileList subfldr.Path, strExtension, enuAttributes, blnSearchSubFolders, GetFileList
            Next
        End If
        For Each f In fldr.Files
            blAddToList = True
            'Build a list of files matching the extension
            'we received
            If InStrRev(strExtension, ".") > 0 Then
                'Match a wildcard filename
                blAddToList = f.Name Like strExtension
            Else
                blAddToList = f.Name Like "*." & strExtension
            End If
            If enuAttributes <> 0 And blAddToList Then
                'Check the file attributes by doing a bitwise and
                'on the attributes property for the specified
                'lngAttributes. If none of the bit(s) we are
                'looking for are set then don't add the file
                If (f.Attributes And enuAttributes) = 0 Then
                    blAddToList = False
                End If
            End If
            If blAddToList Then
                'Add the file to the collection
                GetFileList.Add f, f.Path & " : " & f.Name
            End If
            'Go to the next file in the folder
        Next f
    Else
        'oops
        MsgBox strFolderPath & " does not exist"
    End If
    'Clean up by destroying the reference to the FileSystemObject
    Set fs = Nothing
End Function

Public Function GetActualPathFromRegistry(ByVal FolderName As String) As String
    'Declare the object
    Dim wshShell As Object
    Dim strPath As String
    'Create the Windows Scripting Host Shell object
    Set wshShell = CreateObject("WScript.Shell")
    On Error GoTo errBadRead
    'Read the registry for the appropriate value
    strPath = wshShell.RegRead("HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\" & FolderName)
    'trim it up if necessary, remove %USERPROFILE% value from NT, not required on 2000
    strPath = Right$(strPath, Len(strPath) - (InStr(strPath, "\") - 1))
    'Return the value we found
    GetActualPathFromRegistry = strPath
    'Clean up the object
    Set wshShell = Nothing
    Exit Function
errBadRead:
    'Couldn't find the registry key so return unavailable and clean up
    GetActualPathFromRegistry = "Unavailable"
    Set wshShell = Nothing
End Function
0
 

Author Comment

by:andr
Comment Utility
emoreau,
this is only searching subfolders in the passed folder. I need to loop thru all the subfolders in each subfolder... until the very last subfolder in the tree
0
 
LVL 69

Accepted Solution

by:
Éric Moreau earned 100 total points
Comment Utility
Oups!!!

This is better:

Private Sub Command1_Click()
    Call ScanFolder("D:\emoreau\download")
End Sub

Private Sub ScanFolder(ByVal pstrPath As String)
Dim objFile As File
Dim objFolderChild As Folder
Dim objFolderSource As Folder
Dim objFSO As FileSystemObject

    Set objFSO = New FileSystemObject
(gstrFileName).ParentFolder.ParentFolder.Path
    Set objFolderSource = objFSO.GetFolder(pstrPath)

    For Each objFolderChild In objFolderSource.SubFolders
        Call ScanFolder(objFolderChild.Path)
        For Each objFile In objFolderChild.Files
            List1.AddItem objFolderChild.Path & "\" & objFile.Name
       Next objFile
    Next objFolderChild
End Sub

                   
0
 

Author Comment

by:andr
Comment Utility
Thanks emoreau, that works great.
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

If you have ever used Microsoft Word then you know that it has a good spell checker and it may have occurred to you that the ability to check spelling might be a nice piece of functionality to add to certain applications of yours. Well the code that…
Most everyone who has done any programming in VB6 knows that you can do something in code like Debug.Print MyVar and that when the program runs from the IDE, the value of MyVar will be displayed in the Immediate Window. Less well known is Debug.Asse…
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now