gou*_*gou 1 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
Run Code Online (Sandbox Code Playgroud)
这就是我所说的CopyDirectory方法:
Dim sourcepath As String = "E:\Crazy\"
Dim DestPath As String = "D:\Snippets\"
CopyDirectory(sourcepath, DestPath,)
Run Code Online (Sandbox Code Playgroud)
问题是它不断地一次又一次地复制文件夹.我怎么阻止这个?如何复制子文件夹一次?我用过递归.
你的问题在于:
For Each dir1 As String In Directory.GetDirectories(Path.GetDirectoryName(sourcePath))
Run Code Online (Sandbox Code Playgroud)
这将获取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
Run Code Online (Sandbox Code Playgroud)