Solved

Need help iterating directories

Posted on 2004-03-30
7
163 Views
Last Modified: 2010-05-02
Hello,

I need to write a program that will sweep through a directory (e.g. C:\Program Files\My Software) and any sub-directories and return an array of all the files it finds.

If anyone could point me in the right direction it would be much appreciated.

Many thanks,
Shivermetimbers.
0
Comment
Question by:shivermetimbers
7 Comments
 
LVL 8

Expert Comment

by:dds110
ID: 10713450
0
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 50 total points
ID: 10714278
Option Explicit

Dim fileArray() As String
Dim fileCollection As New Collection

Private Sub Form_Load()
    Dim f As Variant
   
    getFileList "C:\Documents and Settings\Tomlinson\My Documents\DataCD", fileCollection
   
    ' To iterate the files in the collection...
    For Each f In fileCollection
        Debug.Print f
    Next f
   
    ' or if you really need them in an array then...
    convertCollection fileCollection, fileArray
    For f = LBound(fileArray) To UBound(fileArray)
        Debug.Print fileArray(f)
    Next f
End Sub

Private Sub getFileList(startingPath As String, ByRef col As Collection)
    Dim f As Variant
    Dim files As New Collection
   
    ' I found that the Dir() function with no parameters, wasn't working properly
    ' after returning from a recursive call to a subdirectory...so I built the
    ' file list first in a collection, and then make recursive calls after I'm
    ' done making all calls to Dir() for the current directory
   
    'make sure path is in format we want
    If Right(startingPath, 1) <> "\" Then
        startingPath = startingPath & "\"
    End If
   
    ' build file list from current path
    f = Dir(startingPath, vbDirectory)
    Do While f <> ""
         ' Ignore current and parent directory files
        If f <> "." And f <> ".." Then
            files.Add startingPath & f
        End If
        f = Dir ' grab next file entry
    Loop
   
    ' determine if each file was a directory or not
    For Each f In files
        If Not (GetAttr(f) And vbDirectory) = vbDirectory Then
            ' File is not a directory
            col.Add f ' Add it to our collection
        Else
            ' File is a directory
            getFileList f & "\", col ' Make a recursive call to subdirectory
        End If
    Next f
   
    Set files = Nothing
End Sub

Private Sub convertCollection(ByRef col As Collection, ByRef arr As Variant)
    Dim d As Variant
    Dim i As Integer
   
    i = 0
    ReDim arr(col.Count - 1)
    For Each d In col
        arr(i) = d
        i = i + 1
    Next d
End Sub
0
 
LVL 1

Expert Comment

by:dreffed
ID: 10714314
Hi Shivermetimbers...

YOu can use a recursice function and use the FileSystemObject...
In VB6.0
This code will use the filesystem object, and recursively scan the folders, I wrote it to add the files to a treeview

 in the declaration section
private m_files() as string

' in another function
Sub main()
    Dim m_fso As New FileSystemObject
    Dim m_folder As Folder

    Set m_folder = m_fso.getFolder(Me.txtPath.Text)
    scanFiles(m_folder)
End Sub

Private Sub scanFiles(thisFolder As Folder, optional extension As String = "")
    ' recursive function to scan the tree below the current path and
    ' load the files into the tree
    ' if extension is specified then filter
    dim i as long      
    Dim m_file As File
    Dim m_addFile As Boolean
   
    For Each m_file In thisFolder.Files
        ' add this file to the tree view
        ' simple compare, it extension mathces the file extension set the flag,
        ' if not extension is given then add the file.
       If Len(extension) > 0 Then
            If StrComp(Right(m_file.Name, Len(extension)), extension, vbTextCompare) <> 0 Then
                ' don't process this
                m_addFile = False
            Else
                m_addFile = True
            End If
        Else
            m_addFile = True
        End If
       
        ' can we add this file to the array
        If m_addFile Then
            ' get the array size and increment.
            on error resume next
            i = ubound(m_files)
            if err.number <> 0 then
                i = 0
                err.clear
            End If
            i = 1 + 1
           
            ' reinstate the error handler
            on error goto 0
           
            ' load the file details
            redim preserve m_files(i)
            m_files(i) = m_file.Name
        End If
    Next
   
    Dim m_folder As Folder
    For Each m_folder In thisFolder.SubFolders
        scanFiles m_folder, extension
    Next
   
End Sub

I hope this helps

Dreffed
0
 
LVL 17

Expert Comment

by:zzzzzooc
ID: 10714443
The below works for me. Returned the same # of files in the "system32" folder as it does when going to "properties". It's recursive and I just pass the files around as chunks of strings (thought of trying arrays but I'd have to combine them then). As for the reason of "pagefile.sys", it errors when checking it's attribute so I had to ignore it. :] You can modify the attributes to search for also (I decided to have it return system files/etc).

Form1:
---------------

Option Explicit
Private Sub Form_Load()
    Dim sArray() As String, lLoop As Long
    sArray = Split(DirSearchAll("C:\windows\system32\"), vbCrLf)
    For lLoop = LBound(sArray) To UBound(sArray)
        'Print files 1 by 1 to debug window
        Debug.Print sArray(lLoop)
    Next lLoop
    MsgBox UBound(sArray) & " files found!"
End Sub
Private Function DirSearch(ByVal sSearchDir As String, bDir As Boolean) As String
    Dim sDir As String, sFind As String
    sDir = Dir(sSearchDir, vbDirectory + vbHidden + vbNormal + vbSystem + vbReadOnly)
    Do Until sDir = vbNullString
        If sDir <> "." And sDir <> ".." Then
            If bDir = True And sDir <> "pagefile.sys" Then
                If GetAttr(sSearchDir & sDir) And vbDirectory Then
                    DirSearch = DirSearch & sSearchDir & sDir & vbCrLf
                End If
            ElseIf bDir = False And sDir <> "pagefile.sys" Then
                If Not GetAttr(sSearchDir & sDir) And vbDirectory Then
                    DirSearch = DirSearch & sSearchDir & sDir & vbCrLf
                End If
            End If
        End If
        sDir = Dir()
        DoEvents
    Loop
End Function
Private Function DirSearchAll(ByVal sSearchDir As String) As String
    Dim sFiles As String, sDirs As String
    Dim sDirsSplit() As String, lLoop As Integer
    sFiles = DirSearch(sSearchDir, False)
    sDirs = DirSearch(sSearchDir, True)
    sDirsSplit = Split(sDirs, vbCrLf)
    For lLoop = LBound(sDirsSplit) To UBound(sDirsSplit) - 1
        sFiles = sFiles & DirSearchAll(sDirsSplit(lLoop) & "\")
    Next lLoop
    DirSearchAll = sFiles
End Function

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I’ve seen a number of people looking for examples of how to access web services from VB6.  I’ve been using a test harness I built in VB6 (using many resources I found online) that I use for small projects to work out how to communicate with web serv…
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…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…

919 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

15 Experts available now in Live!

Get 1:1 Help Now