• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 200
  • Last Modified:

recursively list the directory ( including sub-directory )

How can I write a dir function to recursively list the files and
even the files in the sub-directory.
Since "dir" function cannot recursively list the files
and I cannot write a recursive function
Any helps
Thanks
0
stanleylcm
Asked:
stanleylcm
1 Solution
 
VbmasterCommented:
Here's a function to do it..

Call it using code like

  Dim Files() As String

  Call ListFiles("C:\Windows\", Files, True)

  'This will fill the array Files with all files inside the C:\Windows\
  'path and all it's subdirectories


Function ListFiles(ByVal Path As String, ByRef av_Array() As String, Recursive As Boolean, Optional IncludePaths As Boolean = True, Optional Prefix As String = "*.*", Optional ByRef x As Double = 0, Optional StartDir As Boolean = True)

  Dim MyName  As String
  Dim MyDir() As String
  Dim MyDirNr As Integer
  Dim a       As Integer
 
  MyDirNr = 0
  If StartDir Then
    x = 0
    Path = IIf(Right$(Path, 1) = "\", Path, Path & "\")
    Prefix = UCase$(Prefix)
  End If
 
  On Error GoTo Errorhandler
 
  MyName = Dir$(Path & "*.*", vbDirectory + vbArchive + vbHidden + vbReadOnly + vbSystem)
  Do While (Len(MyName) > 0)
    If (MyName <> ".") And (MyName <> "..") Then
      If (GetAttr(Path & MyName) And vbDirectory) = vbDirectory Then
        ReDim Preserve MyDir(MyDirNr + 1)
        MyDirNr = MyDirNr + 1
        MyDir(MyDirNr) = MyName
      Else 'If (UCase$(MyName) Like Prefix) Then
        If (x Mod 10 = 0) Then ReDim Preserve av_Array(x + 10)
        x = x + 1
        If IncludePaths Then
          av_Array(x) = Path & MyName
        Else
          av_Array(x) = MyName
        End If
      End If
    End If
    MyName = Dir$
  Loop
 
  If Recursive Then
    For a = 1 To MyDirNr
      If Not ListFiles(Path & MyDir(a) & "\", av_Array(), True, IncludePaths, Prefix, x, False) Then GoTo Errorhandler
    Next
  End If
  If StartDir Then ReDim Preserve av_Array(x)
  ListFiles = True
  Exit Function
 
Errorhandler:
  ListFiles = False

End Function
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now