Google+

Wednesday, August 24, 2011

Encoding Strings to Base64 in C#


I recently had the need to convert simple strings back and forth from Base64 encoding. It turned out to be relatively simple in .Net, once you figured out which class libraries you needed to combine.
It turns out the System.Convert has two handy methods for dealing with Base64, ToBase64String and FromBase64String. On the ToBase64String, we have a bit of a challenge, since it expects a byte array and not a string to be passed in.
It does make a certain amount of sense, typically you aren’t encoding a simple string but instead a binary object such as a file, which is usually represented as an array of bytes. For us, this means we have to take our string and convert it to a byte array.
You’d think the string class would have a nice static method to handle this, but alas it does not. Instead we have to turn to System.Text. I imagine most of you are working with ASCII encoding, so here we’ll call on the ASCIIEncoding.ASCIII class, and use it’s GetBytes to convert a string to bytes.
The small method below combines the two methods I’ve described to create a Base64 encoded string from a normal string.
    static public string EncodeTo64(string toEncode)
    {
      byte[] toEncodeAsBytes
            = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
      string returnValue
            = System.Convert.ToBase64String(toEncodeAsBytes);
      return returnValue;
    }

Note two things, first I am using ASCII encoding, which should cover most folks. Just in case though, System.Text has encodings for the various flavors of UTF as well as Unicode. Just choose the appropriate encoding method for your need.
Second, I made the class static because I was using a console app for my test harness. While it could be static in your class, there’s no reason it has to be. Your choice.
OK, we’ve got the string encoded, at some point we’re going to want to decode it. We essentially do the reverse of encoding, we call the FromBase64String and pass in our encoded string, which returns a byte array. We then call the AsciiEncoding GetString to convert our byte array to a string. Here’s a small method to Decode your Base64 strings.
    static public string DecodeFrom64(string encodedData)
    {
      byte[] encodedDataAsBytes
          = System.Convert.FromBase64String(encodedData);
      string returnValue =
         System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
      return returnValue;
    }

Finally, here’s a simple test harness, done in a console app, to show you calls to the two methods.

      string myData = “Here is a string to encode.”;

      string myDataEncoded = EncodeTo64(myData);
      Console.WriteLine(myDataEncoded);

      string myDataUnencoded = DecodeFrom64(myDataEncoded);
      Console.WriteLine(myDataUnencoded);

      Console.ReadLine();

Be aware, I’ve done no error checking here. My little methods assume that the data you are decoding will properly convert to and from a string. If that’s not the case you could wind up with a serious case of gibberish, if not cause a run time exception. If you are not positive that all you are dealing with is simple strings, then make effort to include some try / catch logic in your implementation.




Note:-Please comment and reply me.

0 comments:

Post a Comment