Florian Müller Florian Müller - 1 year ago 99
Vb.net Question

VB 2010: How to copy all subfolders of a folder in an other folder?

I got a question in Visual Basic 2010: How can I copy all subfolders (only the subfolders, not the main folder) into another folder?

Thanks for the help!



Answer Source

You need to recursivly iterat through all the files and folders and copy them. This method do the job for you:

Public Sub CopyDirectory(ByVal sourcePath As String, ByVal destinationPath As String)
    Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(sourcePath)

    ' If the destination folder don't exist then create it
    If Not System.IO.Directory.Exists(destinationPath) Then
    End If

    Dim fileSystemInfo As System.IO.FileSystemInfo
    For Each fileSystemInfo In sourceDirectoryInfo.GetFileSystemInfos
        Dim destinationFileName As String =
            System.IO.Path.Combine(destinationPath, fileSystemInfo.Name)

        ' Now check whether its a file or a folder and take action accordingly
        If TypeOf fileSystemInfo Is System.IO.FileInfo Then
            System.IO.File.Copy(fileSystemInfo.FullName, destinationFileName, True)
            ' Recursively call the mothod to copy all the neste folders
            CopyDirectory(fileSystemInfo.FullName, destinationFileName)
        End If
End Sub
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download