views:

122

answers:

4

If I want to produce a Base64-encoded output, how would I do that in .NET?

I know that since .NET 2.0, there is the ICryptoTransform interface, and the ToBase64Transform() and FromBase64Transform() implementations of that interface.

But those classes are embedded into the System.Security namespace, and require the use of a TransformBlock, TransformFinalBlock, and so on.

Is there an easier way to base64 encode a stream of data in .NET?

A: 

Richard Grimes posted one here:
http://www.grimes.demon.co.uk/workshops/encodedStream.htm

Also, there's an implementation available under the MS-PL here:
http://cheeso.members.winisp.net/srcview.aspx?file=Base64stream.cs

This latter one lets you do this, for example, to compress then base64-encode a file:

byte[] working= new byte[1024];
int n;
using (Stream input = File.OpenRead(fileToCompress))
{
    using (Stream output = new MemoryStream())
    {
        using (var b64 = new Base64Stream(output, Base64Stream.Mode.Encode))
        {
            b64.Rfc2045Compliant = true; // OutputLineLength = 76;

            using (var compressor = new DeflateStream(b64, CompressionMode.Compress, true))
            {
                while ((n = input.Read(working, 0, working.Length)) != 0)
                {
                    compressor.Write(working, 0, n);
                }
            }
        }
    }
}
Cheeso
You don't need a custom stream class; you can just use a `CryptoStream`. See my answer.
SLaks
+1  A: 

System.Convert provides that, here is a code sample that might help

private string EncodeBase64(string toEncode)
    {
      byte[] toEncodeAsBytes
            = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
      string returnValue
            = System.Convert.ToBase64String(toEncodeAsBytes);
      return returnValue;
    }
Mikos
Useful, but in my case, I don't want to use the ToBase64String. It's not a stream and is likely to not work very well with large data.
Cheeso
+3  A: 

If you want a stream that converts to Base64, you can put a ToBase64Transform into a CryptoStream:

new CryptoStream(stream, new ToBase64Transform(), CryptoStreamMode.Write)

If you just want to convert a single byte array to Base64, you can simply call Convert.ToBase64String(bytes).

In base cases, you can replace the word To with From.

SLaks
Looks easy. Can you set RFC 2045 line lengths on that stream?
Cheeso
You can call `Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks)` However, `ToBase64Transform` does not expose that option.
SLaks
ok that's odd. So if I wanna create a base64 doc for MIME-attach purposes (a la RFC 2045), then I can't used that, but if I convert FROM a base64 doc, it would work?
Cheeso
+1  A: 

This should do what you are looking for:

http://mews.codeplex.com/SourceControl/changeset/view/52969#392973

Andreas Huber