0

我有以下代码将所有内容复制到正确的位置,但文件 1、文件 2 和文件 3 除外。

来源:“C:\dir” 目标:“C:\tmp\Backup”

Public Sub CopyDirectory(source As DirectoryInfo, target As DirectoryInfo)

    'Recursively call the DeepCopy Method for each Directory
    For Each MyDir As DirectoryInfo In source.GetDirectories()
        CopyDirectory(MyDir, target.CreateSubdirectory(projectName & "\" & MyDir.Name))
    Next

    ' Go ahead and copy each file in "source" to the "target" directory
    For Each MyFile As FileInfo In source.GetFiles()

        If Not (File.Exists(Path.Combine(target.FullName, MyFile.Name))) Then
            MyFile.CopyTo(Path.Combine(target.FullName, MyFile.Name))
        Else
            MessageBox.Show("File already exist")
        End If

    Next
End Sub

文件 1、2 和 3 应该放在“Dir”文件夹中,但它一直显示在“Backup”文件夹中。

C:\
|_ tmp
    |_ Backup
        |_ Dir
            |_ Folder 1
                |_ File 11
                |_ File 12
                |_ File 13
            |_ Folder 2
                |_ File 21
                |_ File 22
                |_ File 23
            |_ Folder 3
                |_ File 31
                |_ File 32
                |_ File 33

        |_ File 1
        |_ File 2
        |_ File 3

如何确保将文件 1、2 和 3 复制到“Dir”文件夹中?

4

2 回答 2

0

我认为你的问题在于这一行:

CopyDirectory(MyDir, target.CreateSubdirectory(projectName & "\" & MyDir.Name))

我认为您想在目标处创建新文件夹。为此,您可以这样做:

CopyDirectory(MyDir, target.CreateSubdirectory(MyDir.Name))

嗯,没错。错过了这一行:

来源:“C:\dir” 目标:“C:\tmp\Backup”

你的程序正在做你告诉它做的事情。将目录中的文件放入备份中。如果你想改变它,你需要在开始第一次递归时将目标设置为 C:\temp\Backup\dir。

于 2013-10-09T06:45:43.443 回答
0

代码已更改为以下。谢谢 WozzeC。

最终代码:

                    fullPath = Path.GetFullPath(txtSLocation1.Text).TrimEnd(Path.DirectorySeparatorChar)
                projectName = Path.GetFileName(txtSLocation1.Text)

                Dim SourcePath As New IO.DirectoryInfo(txtSLocation1.Text)
                Dim DestPath As New IO.DirectoryInfo(txtDLocation1.Text & "\" & projectName)

                DestString = txtDLocation1.Text & "\" & projectName
                CopyDirectory(SourcePath, DestPath)

复制目录

Public Sub CopyDirectory(source As DirectoryInfo, target As DirectoryInfo)


    If (Not System.IO.Directory.Exists(DestString)) Then
        System.IO.Directory.CreateDirectory(DestString)
    End If

    'Recursively call the DeepCopy Method for each Directory
    For Each MyDir As DirectoryInfo In source.GetDirectories()
        CopyDirectory(MyDir, target.CreateSubdirectory(MyDir.Name))
    Next

    ' Go ahead and copy each file in "source" to the "target" directory
    For Each MyFile As FileInfo In source.GetFiles()

        If Not (File.Exists(Path.Combine(target.FullName, MyFile.Name))) Then
            MyFile.CopyTo(Path.Combine(target.FullName, MyFile.Name))
        Else
            MessageBox.Show("File already exist")
        End If
    Next
End Sub
于 2013-10-10T03:41:37.003 回答