Append a byte[] to a MemoryStream or another byte[]

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Is there a class that will allow me to append a byte[] to another? The data
that I have is binary so StringBuilder will not work.
 
Is there a class that will allow me to append a byte[] to another? The data
that I have is binary so StringBuilder will not work.

Appending it to a MemoryStream (per your subject line) is easy, just
call the Stream.Write method.

You can't append things to an array since arrays have a fixed length.
But you can create a new array and write both parts to it using
Array.Copy or Buffer.BlockCopy.


Mattias
 
Eric,

You can use an array list, or, if you are using .NET 2.0, you can use a
List<byte>.

Hope this helps.
 
if you want to append to MemoryStream, use Write method, if you want to
merge into two byte[]'s, use static method Array.Copy
 
Eric said:
Is there a class that will allow me to append a byte[] to another?
The data that I have is binary so StringBuilder will not work.

Others have suggested a MemoryStream. I won't. The reason is that it
will cause at least one extra array allocation than you need. Just
allocate the array yourself and use Buffer.BlockCopy, it is simple:

byte[] AppendArrays(byte[] a; byte[] b)
{
byte[] c = new byte[a.Length + b.Length]; // just one array
allocation
Buffer.BlockCopy(a, 0, c, 0, a.Length);
Buffer.BlockCopy(b, 0, c, a.Length, b.Length);
return c;
}

Richard
 
Back
Top