VB 2010: How to copy all subfolders of a folder in an other folder?

隐身守侯 提交于 2019-12-30 05:16:05

问题


I got a question in Visual Basic 2010: How can I copy all subfolders (only the subfolders, not the main folder) into another folder?

Thanks for the help!


回答1:


You need to recursivly iterat through all the files and folders and copy them. This method do the job for you:

Public Sub CopyDirectory(ByVal sourcePath As String, ByVal destinationPath As String)
    Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(sourcePath)

    ' If the destination folder don't exist then create it
    If Not System.IO.Directory.Exists(destinationPath) Then
        System.IO.Directory.CreateDirectory(destinationPath)
    End If

    Dim fileSystemInfo As System.IO.FileSystemInfo
    For Each fileSystemInfo In sourceDirectoryInfo.GetFileSystemInfos
        Dim destinationFileName As String =
            System.IO.Path.Combine(destinationPath, fileSystemInfo.Name)

        ' Now check whether its a file or a folder and take action accordingly
        If TypeOf fileSystemInfo Is System.IO.FileInfo Then
            System.IO.File.Copy(fileSystemInfo.FullName, destinationFileName, True)
        Else
            ' Recursively call the mothod to copy all the neste folders
            CopyDirectory(fileSystemInfo.FullName, destinationFileName)
        End If
    Next
End Sub



回答2:


System.IO has two classes that you can use in a recursive fashion to do this all from code.

  • DirectoryInfo
  • FileInfo

DirectoryInfo has two methods that are relevant:

  • GetDirectories
  • GetFiles

FileInfo has a CopyTo method

Given those objects and methods and a bit of creative recursion you should be able to copy the stuff fairly easily.




回答3:


This seems to be the simplest solution:

For Each oDir In (New DirectoryInfo("C:\Source Folder")).GetDirectories()
    My.Computer.FileSystem.CopyDirectory(oDir.FullName, "D:\Destination Folder", overwrite:=True)
Next oDir


来源:https://stackoverflow.com/questions/5525573/vb-2010-how-to-copy-all-subfolders-of-a-folder-in-an-other-folder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!