Encoding Binary Data as Base64
Problem
You have a byte[] representing some binary information, such as a bitmap. You need to encode this data into a string so that it can be sent over a binary-unfriendly transport such as email.
Solution
Using the static method Convert.ToBase64String on the Convert class, a byte[] may be encoded to its String equivalent:
using System;
public static string Base64EncodeBytes(byte[] inputBytes)
{
return (Convert.ToBase64String(inputBytes));
}
Discussion
The Convert class makes encoding between a byte[] and a String a simple matter. The parameters for this method are quite flexible. It provides the ability to start and stop the conversion at any point in the input byte array.
To encode a bitmap file into a string that can be sent to some destination via email, you can use the following code:
byte[] image = null;
using (FileStream fstrm = new FileStream(@"C:\WINNT\winnt.bmp",
FileMode.Open, FileAccess.Read))
{
using (BinaryReader reader = new BinaryReader(fstrm))
{
byte[] image = new byte[reader.BaseStream.Length];
for (int i = 0; i < reader.BaseStream.Length; i++)
{
image[i] = reader.ReadByte( );
}
}
}
string bmpAsString = Base64EncodeBytes(image);
The bmpAsString string can then be sent as the body of an email message.
To decode an encoded string to a byte[], see Recipe 2.12.
See Also
See Recipe 2.12;see the "Convert.ToBase64CharArray Method" topic in the MSDN documentation.
|