Combining byte arrays

InertiaM

Well-known member
Joined
Nov 3, 2007
Messages
663
Location
Kent, UK
Programming Experience
10+
I'm trying to create a file which includes a string, then a byte array, then a string. The following works :-

VB.NET:
        Dim baFirstLine() As Byte = StrToByteArray("First line" & vbCrLf)
        Dim jpgFile() As Byte = My.Computer.FileSystem.ReadAllBytes("c:\temp.jpg")
        Dim baSecondLine() As Byte = StrToByteArray(vbCrLf & "Second line" & vbCrLf)
        My.Computer.FileSystem.WriteAllBytes("c:\bytearray.bin", baFirstLine, False)
        My.Computer.FileSystem.WriteAllBytes("c:\bytearray.bin", jpgFile, True)
        My.Computer.FileSystem.WriteAllBytes("c:\bytearray.bin", baSecondLine, True)

but is slightly inefficient as it uses 3 WriteAllBytes lines. What's the best way to comine these three byte arrays and then do just one WriteAllBytes line?
 
Think I've worked it out. Comments please :D

VB.NET:
    Public baCombined() As Byte

.....

    Public Sub AddToArray(ByVal whatbytearray() As Byte)
        If baCombined.Length = 1 Then
            ReDim baCombined(whatbytearray.Length - 1)
            whatbytearray.CopyTo(baCombined, 0)
        Else
            Dim intPreviousSize As Int32 = baCombined.Length
            ReDim Preserve baCombined(baCombined.Length + whatbytearray.Length - 1)
            Array.Copy(whatbytearray, 0, baCombined, intPreviousSize, whatbytearray.Length)
        End If
    End Sub


......

        ReDim Preserve baCombined(0)
        AddToArray(baFirstLine)
        AddToArray(jpgFile)
        AddToArray(baSecondLine)
        My.Computer.FileSystem.WriteAllBytes("c:\bytearray3.bin", baCombined, False)
 
Have you thought about using a BinaryWriter ?

Also in case you need to do this sometimes, the easiest way to add up bytes to one array is writing them to a MemoryStream, then ToArray it when you need an array. I don't think you need to here, also opening a FileStream would be better if you were concerned about open/close of file multiple times with the WriteAllBytes method.

Another file storage system that very popular for organizing lots of data is Xml.
 
Back
Top