Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to convert Stream (of unknown length) to byte array, in .NET?

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!

like image 835
Frank Hamming Avatar asked Jun 18 '10 12:06

Frank Hamming


People also ask

Which process converts instance into stream of bytes?

Serialization is the process of converting complex objects into stream of bytes for storage.

How do I get bytes from MemoryStream?

To get the entire buffer, use the GetBuffer method. This method returns a copy of the contents of the MemoryStream as a byte array. If the current instance was constructed on a provided byte array, a copy of the section of the array to which this instance has access is returned.

What is byte stream in C#?

Byte streams comprise classes that treat data in the stream as bytes. These streams are most useful when you work with data that is not in a format readable by humans. Stream Class. In the CLR, the Stream class provides the base for other byte stream classes.

Does MemoryStream copy byte array?

From expirience I can say, that it does not copy the array. Be aware though, that you are unable to resize the memory stream, when using an array in the constructor.


1 Answers

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);
       }
   }
}
like image 158
David Neale Avatar answered Oct 19 '22 13:10

David Neale