Thursday 19 May 2011

Get bytes from Stream in c#

I know you may think what is the need of this post as this is very minor or simple to think and write. But, whenever I need to get bytes from a stream object, I always forgot it. This is simple but most of the times we used to Google. So, planned to write it to remember at least myself next time.
public byte[] GetBytesFromStream(Stream stream)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}