C# base64 encoding and decoding

Today a simple thing, which I always have to lookup because I rarely use it. While communicating with some systems you have to encode the data using base 64 encoding. Base64 encoding is an encoding where every character is encoded using only a..z A..Z 0..9 + and /. This solves problems with special control characters. 

The functionality is built in the .net framework. To Encode a string to base64 you can use:

public static string EncodeTo64(string toEncode)
{
    byte[] arrayToEncode = System.Text.Encoding.Unicode.GetBytes(toEncode);
    return System.Convert.ToBase64String(arrayToEncode);
}

And to decode it, you can use:

public static string DecodeFrom64(string toDecode)
{
    byte[] arrayToDecode = System.Convert.FromBase64String(toDecode);
    return  System.Text.Encoding.Unicode.GetString(arrayToDecode);
}

As you see, these methods are quite similar.

I hope you can use these methods.

Comments are closed.