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

12,253

Solution 1

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);
       }
   }
}

Solution 2

int read = stream.Read (buffer, 0, buffer.Length);

This line will block forever if there is no data Available. Read is a blocking function and it will block the thread until it reads at least one byte but if there is no data then it will block forever.

Solution 3

It looks like your current solution is pretty good. You may consider wrapping it up into an extension method if you'd like the code to look cleaner.

Share:
12,253
Frank Hamming
Author by

Frank Hamming

Updated on June 03, 2022

Comments

  • Frank Hamming
    Frank Hamming almost 2 years

    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!

  • Stephen Cleary
    Stephen Cleary almost 14 years
    This reads to the end of the stream, but the intent is to only read until IsMessageComplete.
  • Frank Hamming
    Frank Hamming almost 14 years
    Thanks for the link to the article; it looks like I'm doing pretty much the same algorithm but with a different terminating condition on the loop.
  • Frank Hamming
    Frank Hamming almost 14 years
    Interesting, I'd never heard of extension methods prior to your post. Thanks for the tip and for looking at my code
  • Ivandro Jao
    Ivandro Jao over 8 years
    @derek-beattie how can I produce this issues?
  • Derek Beattie
    Derek Beattie over 8 years
    @IvandroIsmael abhinaw answered this one
  • Ivandro Jao
    Ivandro Jao over 8 years
    Ohw, I'm sorry mate Derek-Beattie. /cc @abhinaw