Parsing a directory, including sub directory

Posted on 2004-10-15
Last Modified: 2013-11-18
I'm using VB6, and decided to start thinking about a small utility project.  (I prefer to write my own small stuff, as I can usually get it faster than searching for something online.)

This project needs the ability to look through a given directory (folder, whatever), check for either a specific file or type of file (*.mp3, for example), and parse its way through any and all sub folders.  I admit that I haven't looked for the info much, as I have only just begun to plan the project.

Any ideas, including pseudo code would be helpfull.

Question by:Mixael

Accepted Solution

VBtorment earned 30 total points
ID: 12319421
Hai, Mixael

Public Const MAX_PATH = 260
Public Type FILETIME
    dwLowDateTime As Long
    dwHighDateTime As Long
End Type
Public Type WIN32_FIND_DATA
    dwFileAttributes As Long
    ftCreationTime As FILETIME
    ftLastAccessTime As FILETIME
    ftLastWriteTime As FILETIME
    nFileSizeHigh As Long
    nFileSizeLow As Long
    dwReserved0 As Long
    dwReserved1 As Long
    cFileName As String * MAX_PATH
    cAlternate As String * 14
End Type

Public Declare Function GetDriveType Lib "kernel32" Alias "GetDriveTypeA" (ByVal nDrive As String) As Long

Public Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long

Public Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" (ByVal hFindFile As Long, lpFindFileData As WIN32_FIND_DATA) As Long

Public Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long

Public FCount As Long

Sub LoopFolders(sPath$)
Dim hFile As Long
Dim cont As Integer
Dim sFile As String

    cont = True
    sPath$ = bsl(sPath$)
    'find the first file matching the parameter \*.*
    hFile = FindFirstFile(sPath & "*.*" & Chr$(0), WFD)
    If hFile <> -1 Then
        While cont
            sFile = TrimNull(WFD.cFileName)
             'ignore the 2 standard root entries
            If (sFile <> ".") And (sFile <> "..") Then
                If (WFD.dwFileAttributes And vbDirectory) Then
                    FCount = FCount + 1
                    'Do your stuf here for dirs
                    'LoopFolders sPath & sFile 'recurse
                Else    'bestanden
                    'Do your stuf here for Files
                End If
            End If
            cont = FindNextFile(hFile, WFD)
    End If
    Call FindClose(hFile)
End Sub

Public Function bsl(Path$) As String
    If Right$(Path$, 1) = "\" Then
        bsl = Path$
        bsl = Path$ & "\"
    End If
End Function


Assisted Solution

bramsquad earned 30 total points
ID: 12319529
here are some self explanitory function that should help you out

Function GetPath(FullPath As String) As String
    GetPath = Left(FullPath, Len(FullPath) - (InStr(1, StrReverse(FullPath), "\") - 1))
End Function

Function GetExtension(FullPath As String) As String
    GetExtension = Right(FullPath, Len(FullPath) - (InStr(1, (FullPath), ".") - 1))
End Function

Function GetFileName(FullPath As String) As String
    GetFileName = Left(Right(FullPath, Len(FullPath) - (InStr(1, StrReverse(FullPath), ".") - 1)), Len(Right(FullPath, Len(FullPath) - (InStr(1, StrReverse(FullPath), ".") - 1))) - Len(Right(FullPath, Len(FullPath) - (InStr(1, (FullPath), ".") - 1))))
End Function

Function FileExists(FullPath As String) As Boolean
    If Dir(FullPath) = "" Then
        FileExists = False
        FileExists = True
    End If
End Function

LVL 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 25 total points
ID: 12320000
Here is another way to do it using the built in methods from VB (the API method presented by VBtorment is the fastest).  I though I would present this method because it shows how to add the matches to collection.  Create a new project and add a CommandButton, Label and a TextBox.  For the TextBox, set the MultiLine property to True and the ScrollBars property to 3 - Both.

Option Explicit

Private matches As Collection

Private Sub Form_Load()
    Label1.Caption = ""
End Sub

Private Sub Command1_Click()
    Command1.Enabled = False

    Dim match As Variant
    Set matches = New Collection
    findFiles "C:\Documents and Settings\Michael\My Documents\", "*.txt"
    Text1.Text = ""
    For Each match In matches
        Text1.Text = Text1.Text & match & vbCrLf
    Label1.Caption = matches.Count & " file(s) found"
    Command1.Enabled = True
End Sub

Private Sub findFiles(ByVal basePath As String, ByVal filter As String)
    Dim curFile As String
    Dim subdir As Variant
    Dim subDirs As Collection
    ' add matching files in current directory
    curFile = Dir(basePath & filter)
    Do While curFile <> ""
        Label1.Caption = basePath & curFile
        matches.Add basePath & curFile
        curFile = Dir()
    ' build subDirs collection
    Set subDirs = New Collection
    curFile = Dir(basePath, vbDirectory)
        If curFile <> "" Then
            If (GetAttr(basePath & curFile) And vbDirectory) = vbDirectory Then
                If curFile <> "." And curFile <> ".." Then
                    subDirs.Add basePath & curFile & "\"
                End If
            End If
        End If
        curFile = Dir()
    Loop While curFile <> ""
    ' recurse into each subdir
    For Each subdir In subDirs
        findFiles subdir, filter
End Sub


Author Comment

ID: 12320072
All three good answers, and have me pointed in the right direction.  Although I haven't tried any of these answers yet, I shall do so this weekend.  I felt that all three answers were on the mark, and split the points the way I did based only on the order the answers came in.  (I should have increased the point value first, but got ahead of myself.)  To be honest, I didn't expect any answers so soon!

Thanks for the answers.

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

Suggested Solutions

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
You can of course define an array to hold data that is of a particular type like an array of Strings to hold customer names or an array of Doubles to hold customer sales, but what do you do if you want to coordinate that data? This article describes…
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

910 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

22 Experts available now in Live!

Get 1:1 Help Now