【问题标题】:Copy subfolders to another folder in VB.NET without overwriting将子文件夹复制到 VB.NET 中的另一个文件夹而不覆盖
【发布时间】:2012-11-04 20:39:18
【问题描述】:

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

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

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

【问题讨论】:

  • AnyBody 请帮帮我..

标签: vb.net recursion copy overwrite


【解决方案1】:

你的问题在这里:

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

【讨论】:

    猜你喜欢
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多