Quick code snippet: get bytes from stream with C#

Posted: (EET/GMT+2)

 

When you are writing code to use stream objects in your C#/.NET applications, there might sometimes raise the need to get a byte array of all the bytes in the stream. Depending on the stream object, there might be ready-made possiblities for doing this, but here's one generic solution. Although it is not perfect performance-wise (speed and memory consumption), it should do well with smaller streams, like those below 50 KB. Here's the code in C#:

private static byte[] GetBytesFromStream(Stream stream)
{
  List bytes = new List();
  const int blockSize = 1024;
  // copy data block by block
  byte[] buffer = new byte[blockSize];
  int bytesRead = stream.Read(buffer, 0, blockSize);
  while (bytesRead > 0)
  {
    bytes.AddRange(buffer);
    bytesRead = stream.Read(buffer, 0, blockSize);
  }
  return bytes.ToArray();
}

Hope this helps! Keywords: get bytes from stream, copy stream to byte array, read bytes from stream object.