Snippet. C#. Encode and Decode String to/from Base64

The Base64 encoding allows representing binary data in an ASCII string format by translating it into a radix-64 representation. Base64 is heavily used in a number of applications including email, and storing complex data in databases or XML.

Encode String to Base64

//========================= START OF METHOD ===========================//
// METHOD: base64_encode                                               //
//=====================================================================//
String base64_encode(String str) {
    try {
        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
        return Convert.ToBase64String(buffer);
    } catch (Exception e) {
        throw new Exception("Exception in base64_encode: " + e.Message, e);
    }
}
//=====================================================================//
//  METHOD: base64_encode                                              //
//========================== END OF METHOD ============================//

Decode String from Base64

//========================= START OF METHOD ===========================//
// METHOD: base64_decode                                               //
//=====================================================================//
String base64_decode(String str) {
    try {
        byte[] buffer = Convert.FromBase64String(str);
        return System.Text.Encoding.UTF8.GetString(buffer);
    } catch (Exception e) {
        throw new Exception("Exception in base64_decode: " + e.Message, e);
    }
}
//=====================================================================//
//  METHOD: base64_decode                                              //
//========================== END OF METHOD ============================//

Usage

try {
    String str = base64_encode("HELLO");
    System.Diagnostics.Debug.WriteLine(str);
    str = base64_decode(str);
    System.Diagnostics.Debug.WriteLine(str);
} catch(Exception e) {
    System.Diagnostics.Debug.WriteLine("There was exception in Base64 functions");
}          

Updated on: 25 Apr 2024