StreamExtensions – Two nice and simple helper functions for streams

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
  1. public static class StreamExtensions
  2. {
  3. public static void CopyStream(this Stream input, Stream output)
  4. {
  5. byte[] buffer = new byte[32768];
  6. int read;
  7. while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
  8. {
  9. output.Write(buffer, 0, read);
  10. }
  11. output.Seek(0, SeekOrigin.Begin); //
  12. }
  13. public static byte[] GetBytes(this Stream stream)
  14. {
  15. MemoryStream memoryStream = new MemoryStream();
  16. CopyStream(stream, memoryStream);
  17. return memoryStream.GetBuffer();
  18. }
  19. }

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Switch to our mobile site