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]; // 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!
Shamelessly copied from Jon Skeet's article.
public static byte[] ReadFully (Stream stream)
{
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = stream.Read (buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write (buffer, 0, read);
}
}
}