2

我有我用来复制目录的代码:

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,)

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

4

1 回答 1

6

你的问题出在这里:

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

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

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
于 2012-11-16T08:35:06.023 回答