2012-11-16 159 views
1

我有這樣的代碼,我使用的複製目錄:子文件夾複製到VB.NET另一個文件夾中,而不會覆蓋

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

問題是它連續複製文件夾一次又一次。我該如何阻止?我如何一次性複製子文件夾?我用過遞歸。

+0

AnyBody請幫我.. – gou

+0

最後我明白了 – gou

回答

4

你的問題就在這裏:

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 
相關問題