将子文件夹复制到VB.NET中的另一个文件夹而不覆盖

时间:2012-11-16 05:49:22

标签: vb.net recursion copy overwrite

我有这个代码用于复制目录:

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

这就是我调用CopyDirectory方法的方法:

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

问题是它不断地反复复制文件夹。我怎么阻止这个?如何复制子文件夹一次?我使用了递归。

1 个答案:

答案 0 :(得分:5)

你的问题在于:

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

这将获取destPath的父文件夹,而不是从中复制的正确路径 此外,您遇到File.Copy问题。如果文件已存在于目标路径中,则调用File.Copy而不显示覆盖目标的explict请求将引发异常。

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