vb.netrecursiondirectorycreate-directory

VB.NET From Recursive search recreate the folders found in another location


I have a recursive search for all files and subfolders, but I want to create the exact folder structure in another directory.

ay help with this would be greatly appreciated, i have attempted to do this myself as well as looking on the web but i haven't been able to find anything yet.

So i want the folder structure from ConvertDir to be recreated in the SaveDir location, with none of the files. Also I was hoping for these to be created at the same time as they are found, but i do not know if that is even possible or wise.

this will create the folders found on the top level of the SaveDir not in the correct place.

here is a copy of my code:

On Error Resume Next

    Dim ObjFolder
    Dim ObjSubFolders
    Dim ObjSubFolder
    Dim ObjFiles
    Dim ObjFile
    Dim objFileSecuritySettings
    Dim intRetVal
    Dim objSD
    Dim objFolderSecuritySettings

    ObjFolder = FSO.GetFolder(FolderName)
    ObjFiles = ObjFolder.Files

    For Each ObjFile In ObjFiles  'Write all files to output files

        objFileSecuritySettings = _
        objWMIService.Get("Win32_LogicalFileSecuritySetting='" & ObjFile.Path & "'")
        intRetVal = objFileSecuritySettings.GetSecurityDescriptor(objSD)

        If intRetVal = 0 Then

            ObjOutFile.WriteLine(ObjFile.Path) ' write in CSV format

        End If

    Next

    ObjSubFolders = ObjFolder.SubFolders     'Getting all subfolders

    For Each ObjFolder In ObjSubFolders

        objFolderSecuritySettings = _
        objWMIService.Get("Win32_LogicalFileSecuritySetting='" & ObjFile.Path & "'")
        intRetVal = objFolderSecuritySettings.GetSecurityDescriptor(objSD)
        Directory.CreateDirectory(SaveDir + "\\" + ObjFolder.name)

        If intRetVal = 0 Then

            ObjOutFile.WriteLine(ObjFolder.Path) ' write in CSV format
            ObjOutFile.WriteLine(ObjFolder.ObjSubFolders)

        End If

        Gather(ObjFolder.Path)

    Next

Thank you in advance.

AntonSK


Solution

  • You could make the method pass on the root folder that it started at to keep the directory tree intact. And use it as such:

    ReCreateDirectoryStructure("C:\somefolder\", "D:\")
    
    Private Sub ReCreateDirectoryStructure(ByVal sourceDir As String, _
            ByVal targetDir As String, Optional ByVal rootDir As String = "")
        If rootDir = String.Empty Then
            rootDir = sourceDir
        End If
        Dim folders() As String = IO.Directory.GetDirectories(sourceDir)
        For Each folder As String In folders
            Directory.CreateDirectory(folder.Replace(rootDir, targetDir))
            ReCreateDirectoryStructure(folder, targetDir, rootDir)
        Next
    End Sub