Have you ever had the need for a function to copy every file in a directory… wait no longer… here is a recursive way to copy files:
Sub CopySelectedFiles(ByVal strSourceDirectory As String, ByVal strDestDirectory As String, ByVal strSearchString As String)Dim dirInfo As New DirectoryInfo(strSourceDirectory)Dim fsInfo As FileSystemInfoFor Each fsInfo In dirInfo.GetFileSystemInfosDim strDestFileName As String = Path.Combine(strDestDirectory, fsInfo.Name)If TypeOf fsInfo Is FileInfo And fsInfo.Name.IndexOfAny(strSearchString) > -1 ThenFile.Copy(fsInfo.FullName, strDestFileName, True) ' 'This will overwrite files that already existElse
CopySelectedFiles(fsInfo.FullName, strDestFileName, strSearchString) 'we have found a subdirectory
End IfNext
End Sub3 thoughts on “Recursive File Copier Function”
Leave a Reply
I found your function very helpful. The only problem is if the a subdirectory doesn’t exist in the destination location, the function craps out. Is there a way to modify the function so that it creates the necessary subdir at the destination before recursing to copy the contents of that subdir??
I solved my own problem. If you add:
Dim destDirInfo As New DirectoryInfo(strDestFileName)
destDirInfo.Create()
right after the Else before the recurse call, the sudbir will be created.
ah, thanks Mark.
Looks like i may need to update this post, the code is all bunched up on the page.