Archive

Posts Tagged ‘Wrapper’

Convenient MemoryStream Wrapper

December 18th, 2009 Christian Etter No comments

The System.IO.MemoryStream class provides a way of storing binary data of arbitrary length in memory. Frequently, the data source is another System.IO.Stream or a byte array. Unfortunately, the MemoryStream class does not contain a convenient method for reading an entire Stream object in a single call.
The following wrapper does just that. It reads the content of any Stream class passed to it’s contructor and stores it internally:

public class MyMemoryStream : MemoryStream
{
    public MyMemoryStream( Stream s ) : this() { byte[] b = new byte[ 512 ]; int i; while ( ( i = s.Read( b, 0, b.Length ) ) > 0 ) Write( b, 0, i ); }
    public void Write( byte[] b ) { Write( b, 0, b.Length ); }
 }

How to make use of this class? The following example returns a UTF-8 encoded web resource as a String:

public static string GetUri( Uri uri )
{
    HttpWebRequest oRequest = HttpWebRequest.Create( uri ) as HttpWebRequest;
    using ( HttpWebResponse oResponse = oRequest.GetResponse() as HttpWebResponse )
        using ( Stream oStream = oResponse.GetResponseStream() )
            using ( MyMemoryStream oMS = new MyMemoryStream( oStream ) )
                return Encoding.UTF8.GetString( oMS.ToArray() );
}