How do I encode binary data as Base64 string?

Category: System, viewed: 7K time(s).

Encoding binary data into Base64 string representation makes the binary data to be easier to be embedded into a text document, an XML document to be transported between the client and server application.

In this example we read an image file and convert it into string encoded with Base64 digits. The encoded data is not encrypted, it was just obfuscated. To make the data secure you might want to implement encryption on the data.

Let see the code below for binary to Base64 conversion.

using System;
using System.IO;

namespace Kodecsharp.Example.System
{
    public class BinaryToBase64
    {
        public static void Main(string[] args)
        {
            //
            // Prepare a place holder for our image file
            //
            byte[] imageBytes = null;

            //
            // Read the content of image file and store each byte in the 
            // imagesBytes.
            //
            FileStream fs = new FileStream(@"C:\Water lilies.jpg", FileMode.Open, FileAccess.Read);
            BinaryReader reader = new BinaryReader(fs);

            try
            {
                long size = reader.BaseStream.Length;
                imageBytes = new byte[size];
                for (long i = 0; i < size; i++)
                {
                    imageBytes[i] = reader.ReadByte();
                }
            }
            finally
            {
                reader.Close();
                fs.Close();
            }

            //
            // Convert the images bytes into its equivalent string representation
            // encoded with base 64 digit.
            //
            string imageString = Convert.ToBase64String(imageBytes);
            Console.WriteLine("Image String: " + imageString);

            TextWriter writer = new StreamWriter(@"C:\Water lilies.txt");
            writer.WriteLine(imageString);
            Console.ReadLine();
        }
    }
}

Here is a portion of the encoded binary:

QHt52ntY1Hz8Y4mYy/HO19Z9Si4Dkf6/SWlPlgMoy4/TL9Ifo5I/8Aft84B7gyQ0kNf6swvTbZRcLq/b
YzT4juxy6SrIr6h0+wN5ewgt8HRouXtyBdY50BpJ3QOJ59qtdJyb682tlfuNp2lvj3UmSN69QyZsd+ob
jVb6zXn7UWg/zddZA8NJWTe4XUttYTqzdHmDDkuu5nq9Rte2QYa0gjUiv2u/6KqdPe453oOINTmufT/a
HuaP8ANUE8wHp8aXH5R5Nil49BrgfcN7T5672ldMHAWY1YB91VVjwOI2NLz/mtXMtLKq7cV0B3qB8/yd
r2LZ6fl11jHyLHkk1imP5Ip27j/acohniJCI8ftVEVGwOlvZHY6Gn6OkDt/JTkzx+CpYV3q49e7khgb/
Powered by Disqus