如果目标目录中不存在该文件夹,则通过创建文件夹将文件从一个目录复制到另一个目录时遇到一些问题。
例子:
C:\temp\test\1.txt
C:\Data\
如
C:\Data\
不包含“temp”或“test”文件夹,它应该在处理之前创建文件夹1.txt
.复制到
C:\Data\temp\test\1.txt
下面是我的代码。但它不起作用..
Private Sub btnBackup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBackup.Click
Dim sourcepath As String = "C:\temp\test\1.txt"
Dim DestPath As String = "C:\Data\"
CopyDirectory(sourcepath, DestPath)
End Sub
Private Shared Sub CopyDirectory(sourcePath As String, destPath As String)
If Not Directory.Exists(destPath) Then
Directory.CreateDirectory(destPath)
End If
For Each file__1 As String In Directory.GetFiles(sourcePath)
Dim dest As String = Path.Combine(destPath, Path.GetFileName(file__1))
File.Copy(file__1, dest)
Next
For Each folder As String In Directory.GetDirectories(sourcePath)
Dim dest As String = Path.Combine(destPath, Path.GetFileName(folder))
CopyDirectory(folder, dest)
Next
End Sub
最佳答案
以下不是目录。
Dim sourcepath As String = "C:\temp\test\1.txt"
因为你在
Directory.GetFiles(sourcePath)
中使用它作为目录.除此之外,我建议下次详细说明您的问题。该代码引发了有意义的异常,例如
DirectoryNotFoundException
使用适当的路径作为消息或(如果文件存在)IOException
带有消息“目录名称无效”。您应该将其添加到问题中。所以解决方案就是删除
1.txt
从目录名:Dim sourcepath As String = "C:\temp\test\"
如果您只需要复制一个文件,请使用 CopyTo method :
Dim sourcepath As String = "C:\temp\test\"
Dim DestPath As String = "C:\temp\Data\"
If Not Directory.Exists(DestPath) Then
Directory.CreateDirectory(DestPath)
End If
Dim file = New FileInfo("C:\temp\test\1.txt")
file.CopyTo(Path.Combine(DestPath, file.Name), True)
关于.net - 如果该文件夹不存在,如何通过创建文件夹将文件从一个目录复制到另一个目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9207257/