Recursive File Copier Function


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 FileSystemInfo

  For Each fsInfo In dirInfo.GetFileSystemInfos
    Dim strDestFileName As String = Path.Combine(strDestDirectory, fsInfo.Name)

    If TypeOf fsInfo Is FileInfo And fsInfo.Name.IndexOfAny(strSearchString) > -1 Then
      File.Copy(fsInfo.FullName, strDestFileName, True) ' 'This will overwrite files that already exist
    Else
      CopySelectedFiles(fsInfo.FullName, strDestFileName, strSearchString) 'we have found a subdirectory
    End If
  Next
End Sub


		
Advertisements

3 thoughts on “Recursive File Copier Function

  1. 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??

  2. 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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s