我一直在网上搜索,发现了很多有关复制文件的帖子,但是我对在子文件夹中复制文件没有运气。我想要做的是提供一个sourcePath和一个destinationPath。所有文件(包括子文件夹中的文件)都将被复制到destinatioPath中。我摆弄了很多代码,但是无法搜索到子文件夹。
我尝试的代码:但是在文件复制行中的“目标”上出现了一个错误。
Public Sub CopyAllFiles(ByVal sourcePath As String, ByVal destPath As String)
Dim files() As String = IO.Directory.GetFiles(destPath)
For Each file As String In files
' Do work, example
Dim dest As String = Path.Combine(destPath, Path.GetFileName(file))
file.Copy(file, dest, True) ' Added True here to force the an overwrite
Next
End Sub
我尝试过的代码,但它将子文件夹移至desinationPath
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
我也尝试过这段代码,因为它没有提供子文件夹中的文件
Private Function CopyDirectory(sourcedir As String, targetdir As String, overwrite As Boolean) As List(Of String)
Dim failedCopy As List(Of String) = New List(Of String)
Directory.CreateDirectory(targetdir)
Dim files = Directory.GetFiles(sourcedir, "*.*", SearchOption.AllDirectories)
For Each file In files
Dim newfile = file.Replace(sourcedir, targetdir)
Dim fi = New FileInfo(file)
Try
fi.CopyTo(newfile, overwrite)
Catch ex As Exception
failedCopy.Add(file)
End Try
Next
Return failedCopy
End Function
答案 0 :(得分:3)
这应该使您更加亲近
Private Sub DirTestCopyButton_Click(sender As Object, e As EventArgs) Handles DirTestCopyButton.Click
Try
CopyDirectoryContents("c:\temp\", "c:\out")
MessageBox.Show("Copy complete")
Catch ex As Exception
MessageBox.Show(String.Concat("An error occurred: ", ex.Message))
End Try
End Sub
Private Sub CopyDirectoryContents(sourcePath As String, destinationPath As String)
If Not Directory.Exists(sourcePath) Then
Return
End If
If Not Directory.Exists(destinationPath) Then
Directory.CreateDirectory(destinationPath)
End If
For Each filePathString As String In Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories)
Dim fileInfoItem As New FileInfo(filePathString)
Dim newFilePath As String = Path.Combine(destinationPath, fileInfoItem.Name)
If File.Exists(newFilePath) Then
'do something about this
Else
File.Copy(filePathString, newFilePath)
End If
Next
End Sub