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

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

Mattias Sjögren

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
 
N

Nicholas Paldino [.NET/C# MVP]

Eric,

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

Hope this helps.
 
L

Lebesgue

if you want to append to MemoryStream, use Write method, if you want to
merge into two byte[]'s, use static method Array.Copy
 
R

Richard Grimes

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top