Best way to convert Stream (of unknown length) to byte array, in .NET?
Posted
by Frank Hamming
on Stack Overflow
See other posts from Stack Overflow
or by Frank Hamming
Published on 2010-06-18T12:20:47Z
Indexed on
2010/06/18
12:23 UTC
Read the original article
Hit count: 114
Hello, I have the following code to read data from a Stream (in this case, from a named pipe) and into a byte array:
// NPSS is an instance of NamedPipeServerStream
int BytesRead;
byte[] StreamBuffer = new byte[BUFFER_SIZE]; // defined elsewhere (less than total possible message size, though)
MemoryStream MessageStream = new MemoryStream();
do
{
BytesRead = NPSS.Read(StreamBuffer, 0, StreamBuffer.Length);
MessageStream.Write(StreamBuffer, 0, BytesRead);
} while (!NPSS.IsMessageComplete);
byte[] Message = MessageStream.ToArray(); // final data
Could you please take a look and let me know if it can be done more efficiently or neatly? Seems a bit messy as it is, using a MemoryStream. Thanks!
© Stack Overflow or respective owner