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

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.