Solved

Need help iterating directories

Posted on 2004-03-30
7
162 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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Computer crashes, following error message in event manager 5 75
How to debug this code 7 49
Copy a row 12 52
Spell Check in VB6 13 43
Introduction In a recent article (http://www.experts-exchange.com/A_7811-A-Better-Concatenate-Function.html) for the Excel community, I showed an improved version of the Excel Concatenate() function.  While writing that article I realized that no o…
Have you ever wanted to restrict the users input in a textbox to numbers, and while doing that make sure that they can't 'cheat' by pasting in non-numeric text? Of course you can do that with code you write yourself but it's tedious and error-prone …
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…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

707 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

16 Experts available now in Live!

Get 1:1 Help Now