Recursive Copy of Folder Contents

SonicBoomAu

Well-known member
Joined
Oct 30, 2003
Messages
179
Location
Australia
Does anyone know how to copy all the contents of a directory to another location?

I have tried using FileSystemInfo and can get the folder to copy across but not the Files.

Help.
 
heres a quick example i knocked up...
Code:
        Dim folders() As String = IO.Directory.GetDirectories("C:\testing1234\")
        Dim newpath As String = "C:\testing\123\"
        /// create the copy of the main directory ( or rename when moving files )
        If Not IO.Directory.Exists(newpath) Then
            IO.Directory.CreateDirectory(newpath)
        End If
        ///
        /// get all the files in the main directory ( eg: .txt ) and copy to new directory
        Dim mainFiles() As String = IO.Directory.GetFiles("C:\testing1234\")
        Dim fileToCopy As String
        For Each fileToCopy In mainFiles
            Dim f As IO.FileInfo = New IO.FileInfo(fileToCopy)
            IO.File.Copy(fileToCopy, newpath & f.Name & f.Extension)
        Next
        ///
        /// get all the sub-folders and copy to new directory.
        Dim path As String
        For Each path In folders
            Dim di As New IO.DirectoryInfo(path)
            Dim subFile As String = newpath & di.Name & "\"
            IO.Directory.CreateDirectory(subFile)
            /// get the files in the sub-folders and copy to the new sub-directories
            Dim filepath As String
            For Each filepath In IO.Directory.GetFiles(di.FullName)
                Dim fi As New IO.FileInfo(filepath)
                IO.File.Copy(filepath, subFile & fi.Name & fi.Extension)
            Next
        Next
 
Back
Top