Base64 Encoding from C#

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

If you’ve done anything long term in the Web industry, it’s likely that you will have come across “Base64 Encoding” at some point. Base64 is the encryption format used by browsers when implementing very simple username and password form of basic authentication.

If you ask anyone these days, however, for a serious point of view on using it, you’ll likely get laughed at. Base64 is a two-way cipher; so as long as you have the original phrase, it’s easy to reverse it back and get the original text back out of it.

Okay, So if It’s Rubbish, Why Am I Telling You about It?

Well, it turns out that Base64 encoding actually does still have one very good use. It’s great for encoding complex binary files and data into a very simple textual representation that transmits exceptionally easy across text-based protocols such as HTTP.

Hang On. HTTP Allows Transmission of Binary, Right?

Yes it does, but let’s imagine for a moment you wanted to try and save a few requests in your latest ASP.NET MVC project.

What you could do is to embed your images directly into your Web page and then transmit them all at the same time when delivering the original page.

If you’re in any doubt about the validity of this scheme, take a look at the source for Google’s current search page. You’ll see something like this:

Base1
Figure 1: Google search uses Base64-encoded images

Pay close attention to the section in the red rectangle. That’s the Google logo that displays front and center in the page when you load it. In fact, if you watch in the Web debugger when loading the page, you’ll see that 100% of the time, the Google logo is loaded from the cache at high speed every time. Because the images are essentially loaded with the page, the display is instantaneous when your browser loads the view.

What you’re looking at is something called a “base 64 encoded data URL.” This is a fairly new thing that’s been introduced in HTML5, and you can use it not only for images, but for CSS files and JavaScript. Anywhere in your HTML/MVC Views that you can specify any kind of URL, you can use a data URL.

The fun part about this is that .NET includes very easy to use routines for you to generate these Base64 strings. Because the strings are plain text, you also can easily send them using simple text transmission services such as SMS text messages on a mobile phone. However if you find yourself struggling, consider visiting the TechRepublic Academy!

Fire up Visual Studio, and start yourself a new console mode project.

Make sure ‘program.cs’ looks as follows:

using System;
using System.Text;

namespace Builder_Pattern
{
   class Program
   {
      static void Main(string[] args)
      {

         string plainText = "Hello .NET Nuts and bolts";

         var plainTextBytes = Encoding.UTF8.GetBytes(plainText);

         string encodedText = Convert.ToBase64String(plainTextBytes);

         Console.WriteLine("Plain Text : {0}", plainText);
         Console.WriteLine("Encoded Text : {0}", encodedText);

      }
   }
}

When you run this, you should see something like the following:

Base2
Figure 2: The output from out Base64 test

Decoding the string back is just as easy:

using System;
using System.Text;

namespace Builder_Pattern
{
   class Program
   {
      static void Main(string[] args)
      {

         string encodedText = "SGVsbG8gLk5FVCBOdXRzIGFuZCBib2x0cw==";

         var encodedTextBytes = Convert.FromBase64String(encodedText);

         string plainText = Encoding.UTF8.GetString(encodedTextBytes);

         Console.WriteLine("Encoded Text : {0}", encodedText);
         Console.WriteLine("Plain Text : {0}", plainText);

      }
   }
}

Which should output the following information:

Base3
Figure 3: The output from our Base64 decode test

If you look at the two code samples, you’ll see that they operate on byte arrays. We convert the string to bytes, then encode it, and the decoder takes the string and produces an array of byte containing the decoded contents.

This means that encoding and decoding a file is as simple as this:

using System;
using System.IO;

namespace Builder_Pattern
{
   class Program
   {
      static void Main(string[] args)
      {

         var fileBytes = File.ReadAllBytes(@"d:\pele.jpg");

         string encodedFile = Convert.ToBase64String(fileBytes);

         Console.WriteLine("Base 64 Encoded File : {0}", encodedFile);

         var decodedFileBytes = Convert.FromBase64String(encodedFile);

         File.WriteAllBytes(@"d:\newfile.jpg", decodedFileBytes);

      }
   }
}

As you can see, however, it produces a *LOT* of data.

Base4
Figure 4: Beware; Base64 encoding will produce large outputs

The trade off here is that you get instant image loading in exchange for inflating your page size slightly. What you don’t want to be doing is using this for massive detailed images.

Where it does shine is if your Web server is compressing output before delivering it. Because of the nature of Base64, it compresses exceptionally efficiently, so a dense amount of data like that will squash down to a very small size.

Once you’ve Base64 encoded your file, you’ll then need to add the appropriate parts that make it a data URL your browser can understand. You then push can the data into your razor view models using standard MVC output methods.

Describing all the different options a data URL can have is best left to the professionals, however.

Using this method for small images such as icons and logos for your UI make it an effective technique. But, remember, it’s also easy to abuse.

Got a .NET class you want to know more about? Come find me on Twitter as @shawty_ds or pay a visit to ‘Lidnug,’ the ‘Linked .NET users Group’ that I help run, or simply just drop me a comment below. My next post just might cover it.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read