The easiest way to convert a byte array to a stream is using the MemoryStream
class:
Stream stream = new MemoryStream(byteArray);
You're looking for the MemoryStream.Write
method.
For example, the following code will write the contents of a byte[]
array into a memory stream:
byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream();
stream.Write(myByteArray, 0, myByteArray.Length);
Alternatively, you could create a new, non-resizable MemoryStream
object based on the byte array:
byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream(myByteArray);
MemoryStream.Write
is much more memory consuming then new MemoryStream(myByteArray)
MemoryStream
buffer by default (just like with e.g. a list). This can be dealt with easily by using the overload that allows you to set capacity, but is only really useful if you don't expect to write any data to the stream (or if you know how much extra bytes you're likely to need). But I suspect that jitbit might be referring to the fact that a when you use the byte[]
constructor, the array isn't copied - the MemoryStream
refers to the array in the argument. This can be both good and bad, and it's a bit of a shame it isn't documented on MSDN :)
The general approach to write to any stream (not only MemoryStream
) is to use BinaryWriter
:
static void Write(Stream s, Byte[] bytes)
{
using (var writer = new BinaryWriter(s))
{
writer.Write(bytes);
}
}
If you are getting an error with the other MemoryStream examples here, then you need to set the Position to 0.
public static Stream ToStream(this bytes[] bytes)
{
return new MemoryStream(bytes)
{
Position = 0
};
}
Success story sharing
stream.ToArray()
if you want your byte array back.