0

我得到了一个包含完整文件路径的列表,例如:

C:\Users\User1\Desktop\doc1.docx
C:\Backup\passwords.pdf
...

我想用 vb.net 代码将它们复制到文本框中设置的目标位置,但保持文件夹树处于活动状态。例如,我想将所有文件复制到 D:\Backup 这应该是这样的:

D:\Backup\Users\User1\Desktop\doc1.docx
D:\Backup\Backup\passwords.pdf

你知道怎么做吗?

4

3 回答 3

0

感谢您的回答,我有一个时间限制来完成这里的所有事情,所以我得到了自己的工作解决方案,它正在按照我的路径进行:

Dim destinationpath As String
    Dim folderpath As String
    If cb_foldertree.Checked = True Then
        For Each item In FileArray
            destinationpath = txt_destination.Text + Path.GetDirectoryName(item).Remove(0, 2) + "\" + Path.GetFileName(item)
            folderpath = txt_destination.Text + Path.GetDirectoryName(item).Remove(0, 2)
            If Directory.Exists(folderpath) = False Then
                Directory.CreateDirectory(folderpath)
            End If

这确保我只创建包含相关文件的文件夹,因此那里没有空文件夹。你会建议在这里使用 try catch 方法吗?如果没有写作权,会发生什么?

于 2013-08-07T07:33:08.213 回答
0

我的代码示例已完成。您应该能够用一个字符串数组代替 fileList 变量,而不会有太多麻烦,因为 .NET 可以像我在这里做的那样 foreach 一个字符串数组。其余的代码非常简单。我创建 destPath 变量,然后创建路径本身(如果它不存在)。然后我们继续创建目标文件名,然后调用 copy。

此代码将处理路径完整文件名列表或字符串数​​组,其中每个字符串都是路径完整文件名。我还没有测试它是否会创建一个超过 1 级深度的路径名,所以你需要测试那个场景。

为了实现您保持整个路径活动的意图,只需将源文件夹变量更改为 c: 它应该可以正常工作。源文件夹的唯一用途是用空字符串替换指定的源文件夹,以准备将其附加到目标路径,这样就可以满足您的要求。

干杯!

Try
        Dim fileList As New List(Of String)
        Dim sourceFolder As String = "c:\Users\User1"
        fileList.Add("c:\Users\User1\file1.docx")
        fileList.Add("c:\Users\User1\subfolder1\file2.docx")
        Dim destinationPath As String = "c:\backup"
        For Each file As String In fileList
            Dim destPath As String = String.Format("{0}{1}", destinationPath, IO.Path.GetDirectoryName(file).Replace(sourceFolder, ""))
            If Not IO.Directory.Exists(destPath) Then IO.Directory.CreateDirectory(destPath)
            Dim destFile As String = String.Format("{0}{1}", destinationPath, file.Replace(sourceFolder, ""))
            IO.File.Copy(file, destFile, False)
        Next
    Catch ex As Exception

    End Try
于 2013-08-06T19:37:47.747 回答
0

尝试这个:

    Dim FileName As String = "c:\blaat\yadda.txt"
    If Not Directory.Exists(Path.GetDirectoryName(FileName)) Then
        Directory.CreateDirectory(Path.GetDirectoryName(FileName))
    End If

当然,你会把它放在一个 try catch 块中......

于 2013-08-06T15:39:40.317 回答