JoinBinaryFiles - Joining a variable number of binary files into a single file
' Join a variable number of binary files into a single file
'
' Params:
' - resultFile: the complete path of the result file you want to create
' - sourceFiles: the sequence of files whose content will be joined together
'
' Example:
' JoinBinaryFiles("D:\Test.bin", "D:\Source1.bin", "D:\Source2.bin",
' "D:\Source3.bin")
Sub JoinBinaryFiles(ByVal resultFile As String, ByVal ParamArray sourceFiles() _
As String)
' if the result file already exists, delete it
If System.IO.File.Exists(resultFile) Then
System.IO.File.Delete(resultFile)
End If
' create the destination file and open it in write mode
Dim fsw As New System.IO.FileStream(resultFile, _
System.IO.FileMode.CreateNew)
Dim writer As New System.IO.BinaryWriter(fsw)
' open each input file in read mode, and copy its content to the
' destination file
Dim fpath As String
For Each fpath In sourceFiles
Dim fsr As System.IO.FileStream
Dim reader As System.IO.BinaryReader
Try
' create the reader for this file
fsr = New System.IO.FileStream(fpath, System.IO.FileMode.Open, _
System.IO.FileAccess.Read)
reader = New System.IO.BinaryReader(fsr)
' read the binary content and write it to the destination file
writer.Write(reader.ReadBytes(fsr.Length))
Catch e As Exception
' if there is an exception, close the writer and re-throw the
' exception
' so that the routines terminates. The reader is closed in the
' Finally block below
writer.Close()
fsw.Close()
Throw e
Finally
If Not reader Is Nothing Then
reader.Close()
fsr.Close()
End If
End Try
Next
' close the writer
writer.Close()
fsw.Close()
End Sub