如何通过创建文件夹将文件从一个目录复制到另一个目录,如果该文件夹不存在

7
我在将文件从一个目录复制到另一个目录时遇到了问题,需要在目标目录中创建文件夹(如果不存在)以便存放文件。
例如:
源路径: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

有任何错误吗?你使用的是XP还是Windows 7? - Mark Hall
4
当提交问题时,“它不起作用”这样的短语应该被 Stack Overflow 阻止 ;) - Tim Schmelter
2个回答

10

以下不是目录。

Dim sourcepath As String = "C:\temp\test\1.txt"
因为你在Directory.GetFiles(sourcePath)中使用它作为目录。
除此之外,我建议你下次更详细地阐述你的问题。代码引发了有意义的异常,如DirectoryNotFoundException,其中包含适当的路径作为消息,或者(如果文件存在)一个具有消息"The directory name is invalid"IOException。你应该将这些内容添加到问题中。
所以解决方案就是从目录名称中删除1.txt
Dim sourcepath As String = "C:\temp\test\"
如果您只需要复制一个文件,请使用CopyTo方法
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)

我有很多文本文件,但我只想复制1.txt文件。 - user1101157

0
    Dim strMasterResourceDirectory As String
    Dim strDirectory As String

    strDirectory = "C:\TestDestination"
    strMasterResourceDirectory = "TestResource"

   If My.Computer.FileSystem.DirectoryExists(strDirectory) = False Then
        My.Computer.FileSystem.CreateDirectory(strDirectory)
    End If

    ' Loop through each file in the directory
    For Each file As IO.FileInfo In New IO.DirectoryInfo(strDirectory).GetFiles

        If file.Name <> "Thumbs.db" Then

            System.IO.File.Delete(strDirectory & "\" & file.Name)

        End If
    Next

    ' Loop through each file in the directory
    For Each file As IO.FileInfo In New IO.DirectoryInfo(strMasterResourceDirectory).GetFiles

        If file.Name <> "Thumbs.db" Then

            ' copy resource to users local directory

            file.CopyTo(strDirectory & "\" & file.Name)

        End If
    Next

欢迎来到StackOverflow!请考虑为您的代码添加一些解释。谢谢! - Aurasphere

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接