Taking snapshot of a folder structure

Posted by Albert Gareev on Jul 08, 2010 | Categories: Back-endSource code

In the Checking structure of created folders example I used a text file as a source, containing manually prepared folder names to check for. Today I want to show how file/folder structure could be captured automatically.

Data Record Declaration

For this example, data will be stored in Dictionary object serving as a dynamic array of records.
Sample file information record:

Class FileInfo
  'full path
  Public FullPath
  '"FILE" / "FOLDER"
  Public FileType
  'file size to check
  Public FileSize
End Class

Map Folder Structure and Store it in Dictionary

This is a main function. It performs basic verification and initiates the chain of folder mapping calls.

Public Function MapStructure(ByVal sParentFolder, ByVal sSubFolder, ByRef objDataRecord)
Dim objFSO

Set objFSO = CreateObject("Scripting.FileSystemObject")

boolRC = objFSO.FolderExists(sParentFolder & "\" & sSubFolder)
If Not boolRC Then
    Set objFSO = Nothing
    MapStructure = False
    Exit Function
End If

Set objFSO = Nothing

Set objDataRecord= CreateObject("Scripting.Dictionary")

Call MapFolder(sParentFolder & "\" & sSubFolder, objDataRecord)

MapStructure = True

End Function

Recursively Map Folder Contents

Any folder can contain files and other folders. For that reason, I will use a recursive calls approach.

Private Function MapFolder(ByVal sTargetFolder, ByRef objDictionary)
Dim FSO, objFolder, objChild
Dim objFI

Set FSO = CreateObject("Scripting.FileSystemObject")

Set objFolder = FSO.GetFolder(sTargetFolder)

'write about itself
Set objFI= New FileInfo
objFI.FileType = "FOLDER"
objFI.FullPath = objFolder.Path
objFI.FileSize = 0
Call objDictionary.Add(objDictionary.Count + 1, objFSR)

'write about child files
For Each objChild In objFolder.Files
    Call objDictionary.Add(objDictionary.Count + 1, MapFile(objChild))

'Call recursively to write about subfolders
For Each objChild In objFolder.SubFolders
    Call MapFolder(objChild.Path, objDictionary)

Set FSO = Nothing

End Function

Map Single File Information

For this example, file path and file size are captured.

Private Function MapFile(ByRef objFile)
Dim objFI

Set objFI= New FileInfo
objFI.FileType = "FILE"
objFI.FullPath = objFile.Path
objFI.FileSize = objFile.Size

Set XCC_MapFile= objFI

End Function

Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported
This work by Albert Gareev is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported.