Skip to content

Base64EncoderStream Base64DecoderStream

jamesfoster edited this page Feb 2, 2012 · 1 revision
var output = new FileStream("output.txt", FileMode.OpenOrCreate, FileAccess.Write)
var input = new FileStream("input.txt", FileMode.Open, FileAccess.Read)

using(output)
using(var base64Encoder = input.Base64Encoder())
{
  base64Encoder.CopyTo(output);
}

In this example we read from input.txt, convert it to base64 using the Base64EncoderStream and write the output to output.txt. Notice input is not directly disposed inside a using() statement but it will be disposed when base64Encoder is disposed.

The Base64DecoderStream works in exactly the same way except it expects the input to be properly formatted base64. By default it will ignore any whitespace in the input stream but you can override that to be more strict. If the input is not valid base64 an Exception will be thrown when you attempt to read.

using(var base64Decoder = input.Base64Decoder(Base64DecodeMode.DoNotIgnoreWhiteSpaces))
{
  base64Decoder.CopyTo(output);
}
Clone this wiki locally