如何迭代文件夹和复制文件

时间:2013-10-09 06:24:12

标签: asp.net .net vb.net

我有以下代码将所有内容复制到正确的位置,但文件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”文件夹,但它会一直显示在“备份”文件夹中。

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”文件夹中?

2 个答案:

答案 0 :(得分:0)

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

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

我认为你想在目标上创建新文件夹。要做到这一点,你要这样做:

CopyDirectory(MyDir, target.CreateSubdirectory(MyDir.Name))
嗯,对。错过了这一行:

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

您的程序正在按照您的要求执行操作。获取目录中的文件并将其置于备份中。如果要更改,则需要在启动第一次递归时将目标设置为C:\ temp \ Backup \ dir。

答案 1 :(得分: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)

CopyDirectory

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