Monday, 5 November 2012

Base 64 encoding strings

Encoding strings to base 64 is super trivial...

The code.


    using System;
    using System.Text;
 
    public static class StringExtensions
    {
        public static string Base64Encode(this string text)
        {
            byte[] bytes = new UTF8Encoding().GetBytes(text);
            string base64EncodedText = Convert.ToBase64String(bytes);
            return base64EncodedText;
        }
 
        public static string Base64Decode(this string base64EncodedText)
        {
            byte[] bytes = Convert.FromBase64String(base64EncodedText);
            string text = new UTF8Encoding().GetString(bytes);
            return text;
        }
    }


The test.


    using Microsoft.VisualStudio.TestTools.UnitTesting;
 
    [TestClass]
    public class StringExtensionsTests
    {
        [TestMethod]
        public void TestEncodeAndDecode()
        {
            const string OrginalText = "originalText";
            string encodedText = OrginalText.Base64Encode();
            Assert.AreNotEqual(OrginalText, encodedText, "The encoded text was the same as the original plain text.");
            string decodedText = encodedText.Base64Decode();
            Assert.AreEqual(OrginalText, decodedText, "The decoded text was not the same as the original plain text.");
        }
    }


And that is it.

Not sure why there aren't such methods in the Base Class Libraries (BCL).

About Me