Pages

Thursday, March 29, 2012

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:
///
/// This method creates a Base64 encoded string from an input
/// parameter string.
///

/// The String containing the characters
/// to be encoded.
/// The Base64 encoded string.

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:
///
/// This method will Decode a Base64 string.
///

/// The String containing the characters
/// to be decoded.
/// A String containing the results of decoding the
/// specified sequence of bytes.

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

No comments: