gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:47:10 26 4
gpt4 key购买 nike

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

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

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

最佳答案

你的问题出在这里:

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

关于vb.net - 将子文件夹复制到 VB.NET 中的另一个文件夹而不覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13411206/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com