devxlogo

SynchronizeDirectoryTrees – Synchronize files in two directory trees

SynchronizeDirectoryTrees – Synchronize files in two directory trees

' Synchronize two directory subtrees'' This routine compares source and dest directory trees and copies files' from source that are newer than (or are missing in) the destination directory' if TWOWAYSYNC is True, files are synchronized in both ways' NOTE: requires the CompareDirectories and SynchronizeDirectories routines'       and a reference to the Microsoft Scripting Runtime type librarySub SynchronizeDirectoryTrees(ByVal sourceDir As String, _    ByVal destDir As String, Optional ByVal TwoWaySync As Boolean)    Dim fso As New Scripting.FileSystemObject    Dim sourceFld As Scripting.Folder    Dim destFld As Scripting.Folder    Dim fld As Scripting.Folder    Dim col As New Collection        ' we need this in case the dest subdir doesn't exist    On Error Resume Next        ' get reference to source and dest folder objects    Set sourceFld = fso.GetFolder(sourceDir)    Set destFld = fso.GetFolder(destDir)    ' create the destination directory, if necessary    If Err Then        ' if the destination directory doesn't exist,        '  create it and copy all files there        ' (this is all we need)        fso.CopyFolder sourceDir, destDir        ' nothing else to do        Exit Sub    End If        ' synchronize the root directories    SynchronizeDirectories sourceDir, destDir, TwoWaySync        ' ensure that dir names have a training backslash    If Right$(sourceDir, 1)  "" Then sourceDir = sourceDir & ""    If Right$(destDir, 1)  "" Then destDir = destDir & ""        ' repeat for all the subdirectories in the source directory    For Each fld In sourceFld.SubFolders        ' remember that we have processed this subdir        col.Add fld.Name, fld.Name                ' call this routine recursively        SynchronizeDirectoryTrees fld.Path, destDir & fld.Name, TwoWaySync    Next        ' if two-way synchronization was requested, ensure that all subdirs in dest    ' directories are copied into source directory    If TwoWaySync Then        For Each fld In destFld.SubFolders            If col(fld.Name) = "" Then                ' we get here only if the folder name isn't in COL,                '  and therefore                ' if this subdirectory isn't in the source directory                fso.CopyFolder fld.Path, sourceDir & fld.Name            End If        Next    End IfEnd Sub

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist