Handling streams can sometimes be a little pain, especially if you simply like to get the byte[] of a stream. As this sounds straightforward this is at the moment only possible for MemoryStreams, which has the function GetBuffer. My approach is straightforward as well. We will just copy the contents of your stream into a new MemoryStream and then get the byte[] buffer. The following class has two methods. CopyStream simply clones the contents of one stream to another. GetBytes returns get byte[] of a stream by copying it first to a MemoryStream and then returning its contents by using GetBuffer.
Code Snippet
- public static class StreamExtensions
- {
- public static void CopyStream(this Stream input, Stream output)
- {
- byte[] buffer = new byte[32768];
- int read;
- while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
- {
- output.Write(buffer, 0, read);
- }
- output.Seek(0, SeekOrigin.Begin); //
- }
- public static byte[] GetBytes(this Stream stream)
- {
- MemoryStream memoryStream = new MemoryStream();
- CopyStream(stream, memoryStream);
- return memoryStream.GetBuffer();
- }
- }

About me