Wednesday, April 13, 2011

C# How To Encode or Decode a String to Base64 UTF-8

This example uses the .NET Framework 4 Encoding Class to Base64 Encode and Decode a supplied sting in your C# Application. The example syntax can be used in any ASP.Net or Win32 program.In addition to the UTF-8 example I've supplied below, the framework also supports methods for encoding/decoding ASCIIEncoding, UnicodeEncoding, UTF32Encoding, UTF7Encoding and UTF8Encoding. 

Assumptions: Your project contains these 3 controls (Label1, TextBox1, Button1)
protected void Button1_Click(object sender, EventArgs e)
{
    Label1.Text = EncodeTo64UTF8(TextBox1.Text.ToString());
}

C# Base64 Encoding Method:
/// <summary>
/// This method creates a Base64 encoded string from an input
/// parameter string.
/// </summary>
/// <param name="m_enc">The String containing the characters
/// to be encoded.</param>
/// <returns>The Base64 encoded string.</returns>

public static string EncodeTo64UTF8(string m_enc)
{
    byte[] toEncodeAsBytes =
    System.Text.Encoding.UTF8.GetBytes(m_enc);
    string returnValue =
    System.Convert.ToBase64String(toEncodeAsBytes);
    return returnValue;
}

C# Base64 Decoding Method:
/// <summary>
/// This method will Decode a Base64 string.
/// </summary>
/// <param name="m_enc">The String containing the characters
/// to be decoded.</param>
/// <returns>A String containing the results of decoding the
/// specified sequence of bytes.</returns>

public static string DecodeFrom64(string m_enc)
{
    byte[] encodedDataAsBytes =
    System.Convert.FromBase64String(m_enc);
    string returnValue =
    System.Text.Encoding.UTF8.GetString(encodedDataAsBytes);
    return returnValue;
}
Reference: http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx

1 comment:

Pravesh Singh said...

Hi,

I was reading your article and I would like to appreciate you for making it very simple and understandable. This article gives me a basic idea of Encoding and Decoding in ASP.Net and it will help me a lot. I had found another nice post with wonderful explanation on Encoding and Decoding in ASP.Net, for more details check out this link....
Encoding and Decoding in ASP.Net

Thank you very much!