我在Visual Basic 2010中遇到一个问题:如何将所有子文件夹(只有子文件夹,而不是主文件夹)复制到另一个文件夹中?
感谢您的帮助!
答案 0 :(得分:13)
您需要递归遍历所有文件和文件夹并复制它们。这种方法可以帮到你:
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
答案 1 :(得分:2)
System.IO有两个类,您可以以递归方式使用它们从代码中完成所有操作。
DirectoryInfo有两个相关的方法:
FileInfo有一个CopyTo方法
鉴于这些对象和方法以及一些创意递归,您应该能够轻松地复制这些内容。
答案 2 :(得分:0)
这似乎是最简单的解决方案:
For Each oDir In (New DirectoryInfo("C:\Source Folder")).GetDirectories()
My.Computer.FileSystem.CopyDirectory(oDir.FullName, "D:\Destination Folder", overwrite:=True)
Next oDir