VB 2010: How to copy all subfolders of a folder to another folder?

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

Thanks for the help!

+4
source share
3 answers

You need to recursively iterate all files and folders and copy them. This method does your job:

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 
+12
source

System.IO has two classes that you can use in a recursive way to make all of this out of code.

  • DirectoryInfo
  • Fileinfo

DirectoryInfo has two suitable methods:

  • Getdirectories
  • Getfiles

FileInfo has CopyTo method

Given these objects and methods and a bit of creative recursion, you should be able to copy material quite easily.

+2
source

This is perhaps 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 
0
source

Source: https://habr.com/ru/post/1346379/


All Articles