It’s inevitable. Eventually every .NET developer will end up working with a Stream object. Either to accept a file uploaded through a form, to retrieve file data from a database, or to keep some data in memory for some temporary processing. And they suck.

You’ll need to buffer streams, convert them to byte arrays, move through them, move them around, copy them .. it’s a pain, really.

Here’s how I deal with it:

namespace ExampleIncorporated
{
    using System;
    using System.IO;

    public static class StreamExtensions
    {
        public static byte[] ToByteArray(this Stream DataStream)
        {
            // If the input stream is null, empty, or unreadable, exit.
            if (DataStream == null || DataStream.Length == 0 || !DataStream.CanRead)
                return null;

            // Get the length of the stream
            int l_ContentLength = Convert.ToInt32(DataStream.Length);

            // Create our byte array with the proper length
            byte[] l_Data = new byte[l_ContentLength];

            // Fill the data array
            DataStream.Read(l_Data, 0, l_ContentLength);

            return l_Data;
        }

        public static void CopyTo(this Stream DataStream, ref Stream OutputStream)
        {
            // Clear the output stream
            OutputStream.Flush();

            // Get the data in a byte array
            byte[] data = DataStream.ToByteArray();

            // If it's null or empty, don't perform the copy.
            if (data == null || data.Length == 0)
                return;

            // Write the data to the output stream
            OutputStream.Write(data, 0, data.Length);
        }
    }
}

Drop that class anywhere in your project. That’ll take care of copying a stream and getting the data out of a stream and into a byte array. KNOWN LIMITATION: Both of these methods will handle a max of 2GB of data. If you’re dealing with more data, you’ll need to modify them to buffer the 2GB max at a time.