gou
gou

Reputation: 40

Copy subfolders to another folder in VB.NET without overwriting

I have this code which I am using to copy a directory:

Private Sub CopyDirectory(ByVal sourcePath As String, ByVal destPath As String)
    If Not Directory.Exists(destPath) Then
        Directory.CreateDirectory(destPath)
    End If

    For Each file1 As String In Directory.GetFiles(sourcePath)
        Dim dest As String = Path.Combine(destPath, Path.GetFileName(file1))
        File.Copy(file1, dest)
    Next

    For Each dir1 As String In Directory.GetDirectories(Path.GetDirectoryName(sourcePath))
        Dim destdir As String = Path.Combine(destPath, Path.GetFileName(dir1))
        CopyDirectory(dir1, destdir)
    Next
End Sub

And this is how I call CopyDirectory method:

 Dim sourcepath As String = "E:\Crazy\"
 Dim DestPath As String = "D:\Snippets\"
 CopyDirectory(sourcepath, DestPath,)

The problem is that it continously copies the folder again and again. How do I stop this? And how do I copy the subfolder a single time? I have used recursion.

Upvotes: 2

Views: 2949

Answers (1)

Steve
Steve

Reputation: 216358

Your problem lies here:

For Each dir1 As String In Directory.GetDirectories(Path.GetDirectoryName(sourcePath))

This will get the parent folder of the destPath, not the correct path to copy from.
Also, you have a problem with File.Copy. If the file already exist in the destination path, calling File.Copy without an explict request to overwrite the destination will throw an exception.

Private Sub CopyDirectory(ByVal sourcePath As String, ByVal destPath As String)  

    If Not Directory.Exists(destPath) Then
        Directory.CreateDirectory(destPath)
    End If

    For Each file1 As String In Directory.GetFiles(sourcePath)
        Dim dest As String = Path.Combine(destPath, Path.GetFileName(file1))
        File.Copy(file1, dest, True)  ' Added True here to force the an overwrite 
    Next

    ' Use directly the sourcePath passed in, not the parent of that path
    For Each dir1 As String In Directory.GetDirectories(sourcePath)
        Dim destdir As String = Path.Combine(destPath, Path.GetFileName(dir1))
        CopyDirectory(dir1, destdir)
    Next
End Sub

Upvotes: 6

Related Questions