Recursive File copy in VB.NET
VB.NET does provide System.IO.File.Copy method to perform simple file copies but doesn’t provide any built in functions to allow for directory copies like VB had in FileCopy().
Here is a very useful function that does recursive file copies with all the bells and whistles that I developed while making the proxy pack application. It recursively copies all files from source to the destination directory and comes complete with flags to allow or deny overwrite & recursive copies. This can be easily re-written in C# also.
‘ Recursively copy all files and subdirectories from the
‘ specified source to the specified destination.
Private Sub RecursiveCopyFiles( _
ByVal sourceDir As String, _
ByVal destDir As String, _
ByVal fRecursive As Boolean, ByVal overWrite As Boolean)
Dim i As Integer
Dim posSep As Integer
Dim sDir As String
Dim aDirs() As String
Dim sFile As String
Dim aFiles() As String
‘ Add trailing separators to the supplied paths if they don’t exist.
If Not sourceDir.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()) Then
sourceDir &= System.IO.Path.DirectorySeparatorChar
End If
If Not destDir.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()) Then
destDir &= System.IO.Path.DirectorySeparatorChar
End If
‘ Recursive switch to continue drilling down into dir structure.
If fRecursive Then
‘ Get a list of directories from the current parent.
aDirs = System.IO.Directory.GetDirectories(sourceDir)
For i = 0 To aDirs.GetUpperBound(0)
‘ Get the position of the last separator in the current path.
posSep = aDirs(i).LastIndexOf(“\”)
‘ Get the path of the source directory.
sDir = aDirs(i).Substring((posSep + 1), aDirs(i).Length – (posSep + 1))
‘ Create the new directory in the destination directory.
System.IO.Directory.CreateDirectory(destDir + sDir)
‘ Since we are in recursive mode, copy the children also
RecursiveCopyFiles(aDirs(i), (destDir + sDir), fRecursive, overWrite)
Next
End If
‘ Get the files from the current parent.
aFiles = System.IO.Directory.GetFiles(sourceDir)
‘ Copy all files.
For i = 0 To aFiles.GetUpperBound(0)
‘ Get the position of the trailing separator.
posSep = aFiles(i).LastIndexOf(“\”)
‘ Get the full path of the source file.
sFile = aFiles(i).Substring((posSep + 1), aFiles(i).Length – (posSep + 1))
Try
‘ Copy the file.
System.IO.File.Copy(aFiles(i), destDir + sFile, False)
addToConsoleWindow(“Copied ” & sFile & ” to ” & destDir)
Catch ex As Exception
If overWrite = False Then
errorBoxShow(ex.Message)
addToConsoleWindow(“Skipping…” & ex.Message)
Else
System.IO.File.Copy(aFiles(i), destDir + sFile, True)
addToConsoleWindow(“Overwriting old ” & sFile & ” in ” & destDir)
End If
End Try
Next i
End Sub