Recipe2.11.Encoding Binary Data as Base64


Recipe 2.11. 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.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

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