Converting from Byte Arrays to Streams and Back

M

Matt

I just wanted to know if I am converting to/from streams the easiest and
correct way. I am performing the following statements to convert byte
arrays to and from streams during different processing in my application:

Here is a sample where I convert from a stream to a byte array:

strm = mqMsg.BodyStream;
BinaryReader br = new BinaryReader(strm);
byteArray= br.ReadBytes(Convert.ToInt32(strm.Length));

Here is a sample where I convert from a byte array to a stream:

MemoryStream memStream = new MemoryStream();
BinaryWriter binWriter = new BinaryWriter(memStream);
binWriter.Write(byteArray);


Thanks,

Matt
 
N

Nicholas Paldino [.NET/C# MVP]

Matt,

That's pretty much how I would do it if I needed the complete array.
The only change I would make is that I would pass the byte array to the
constructor of the memory stream (since you are just reading and writing
bytes, right?). That would eliminate one line of code (which is always a
good thing).

Hope this helps.
 
J

Jon Skeet [C# MVP]

Matt said:
I just wanted to know if I am converting to/from streams the easiest and
correct way. I am performing the following statements to convert byte
arrays to and from streams during different processing in my application:

Here is a sample where I convert from a stream to a byte array:

strm = mqMsg.BodyStream;
BinaryReader br = new BinaryReader(strm);
byteArray= br.ReadBytes(Convert.ToInt32(strm.Length));

Don't forget that Length isn't available on all streams. I would
personally use a method like the one I've got at the bottom of
http://www.yoda.arachsys.com/csharp/readbinary.html

That's basically what BinaryReader is going to be doing anyway, and
there's no need to create a new object (the BinaryReader) to do that :)
Here is a sample where I convert from a byte array to a stream:

MemoryStream memStream = new MemoryStream();
BinaryWriter binWriter = new BinaryWriter(memStream);
binWriter.Write(byteArray);

Why bother with the BinaryReader or BinaryWriter, out of interest? For
the latter example, just use:

MemoryStream memStream = new MemoryStream();
memStream.Write(byteArray, 0, byteArray.Length);

That's assuming you want them to be independent copies - you can make a
memory stream backed by a byte array using one of the MemoryStream
constructors.
 

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