Friday, May 27, 2011

Builtin Base64 Streaming

Months ago I’ve blogged on how to implement base64 streaming reader and writer. Just for the record – the same can be achieved using built-in classes:

class Program
{
    static void Main( string[] args )
    {
        string Original = "foo bar, this is an example";
        byte[] ToBase64;
        string Decoded;
 
        using ( MemoryStream ms = new MemoryStream() )
        using ( CryptoStream cs = new CryptoStream( ms, new ToBase64Transform(),
                                                        CryptoStreamMode.Write ) )
        using ( StreamWriter st = new StreamWriter( cs ) )
        {
            st.Write( Original );
            st.Flush();
 
            ToBase64 = ms.ToArray();
        }
 
        using ( MemoryStream ms = new MemoryStream( ToBase64 ) )
        using ( CryptoStream cs = new CryptoStream( ms, new FromBase64Transform(), 
                                                        CryptoStreamMode.Read ) )
        using ( StreamReader sr = new StreamReader( cs ) )
            Decoded = sr.ReadToEnd();
 
        Console.WriteLine( Original );
        Console.WriteLine( Encoding.Default.GetString( ToBase64 ) );
        Console.WriteLine( Decoded );
 
        Console.ReadLine();
    }
}

The output of above snippet is:

foo bar, this is an example
Zm9vIGJhciwgdGhpcyBpcyBhbiBleGFtcGxl
foo bar, this is an example

2 comments:

Unknown said...

This helped get me going, thank you.

If you try input strings of slightly different lengths, your output will differ. Another post led me to try the following slight mod, which worked:

static void myCryptoBase64()
{
string Original = @"foo bar, this is an exampl abcdefghijklmnopqrstuvwxyz 1234567890 AB";
byte[] ToBase64;
string Decoded;

using ( MemoryStream ms = new MemoryStream() ){
using ( CryptoStream cs = new CryptoStream( ms, new ToBase64Transform(), CryptoStreamMode.Write ) ){
using ( StreamWriter st = new StreamWriter( cs ) )
{
st.Write( Original );
st.Flush();
}
}
ToBase64 = ms.ToArray();
}
using ( MemoryStream ms = new MemoryStream( ToBase64 ) ){
using ( CryptoStream cs = new CryptoStream( ms, new FromBase64Transform(FromBase64TransformMode.DoNotIgnoreWhiteSpaces), CryptoStreamMode.Read ) ){
using ( StreamReader sr = new StreamReader( cs ) )
Decoded = sr.ReadToEnd();
}
}
Console.WriteLine( Original );
Console.WriteLine( Encoding.Default.GetString( ToBase64 ) );
Console.WriteLine( Decoded );

Console.ReadLine();
}

Don

Unknown said...

Hello,
How can I reverse this?
How to read a large base64 string an create a byte array from it?