Recipe 2.11 Encoding Binary Data as Base64

Problem

You have a byte[] , which could represent 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 . ToBase64CharArray on the Convert class, a byte[] may be encoded to a char[] equivalent, and the char[] can then be converted to a string :

 using System; public static string Base64EncodeBytes(byte[] inputBytes)  {     // Each 3-byte sequence in inputBytes must be converted to a 4-byte      // sequence      long arrLength = (long)(4.0d * inputBytes.Length / 3.0d);     if ((arrLength  % 4) != 0)      {         // increment the array length to the next multiple of 4          //    if it is not already divisible by 4         arrLength += 4 - (arrLength % 4);     }     char[] encodedCharArray = new char[arrLength];     Convert.ToBase64CharArray(inputBytes, 0, inputBytes.Length, encodedCharArray, 0);     return (new string(encodedCharArray)); } 

Discussion

The Convert class makes encoding between a byte[] and a char[] and/or a string a simple matter. The ToBase64CharArray method fills the specified character array with converted bytes, and also returns an integer specifying the number of elements in the resulting byte[] , which, in this recipe, is discarded. As you can see, 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 and to add elements starting at any position in the resulting char[] .

To encode a bitmap file into a string that can be sent to some destination via email, you could use the following code:

 FileStream fstrm = new FileStream(@"C:\WINNT\winnt.bmp", FileMode.Open, FileAccess.Read); 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( ); } reader.Close( ); fstrm.Close( ); 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.



C# Cookbook
C# 3.0 Cookbook
ISBN: 059651610X
EAN: 2147483647
Year: 2003
Pages: 315

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net