Base64 Encoding in C#

C# provides built-in support for base64 encoding/decoding.

using System;
using System.Text;

class Base64Example
{
    static void Main()
    {
        // Here's the string we'll encode/decode.
        string data = "abc123!?$*&()'-=@~";

        // C# supports both standard and URL-compatible base64.
        // Here's how to encode using the standard encoder.
        string sEnc = Convert.ToBase64String(Encoding.UTF8.GetBytes(data));
        Console.WriteLine(sEnc);

        // Decoding may throw an exception, which you can catch
        // if you're not sure about the input being well-formed.
        try
        {
            byte[] sDec = Convert.FromBase64String(sEnc);
            Console.WriteLine(Encoding.UTF8.GetString(sDec));
        }
        catch (FormatException)
        {
            Console.WriteLine("Invalid Base64 string");
        }
        Console.WriteLine();

        // This encodes/decodes using a URL-compatible base64 format.
        string uEnc = Convert.ToBase64String(Encoding.UTF8.GetBytes(data)).Replace('+', '-').Replace('/', '_');
        Console.WriteLine(uEnc);
        string uDec = Encoding.UTF8.GetString(Convert.FromBase64String(uEnc.Replace('-', '+').Replace('_', '/')));
        Console.WriteLine(uDec);
    }
}

The string encodes to slightly different values with the standard and URL base64 encoders (trailing + vs -) but they both decode to the original string as desired.

$ dotnet run
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~

In C#, we use the Convert class for Base64 encoding and decoding. The ToBase64String method is used for encoding, while FromBase64String is used for decoding. For URL-safe encoding, we manually replace the characters ‘+’ and ‘/’ with ‘-’ and ‘_’ respectively.

Unlike the Go example, C# doesn’t have a built-in URL-safe Base64 encoder, so we implement it manually by replacing characters after encoding. When decoding, we reverse this process before calling FromBase64String.

Error handling in C# is typically done using try-catch blocks, which is demonstrated in the decoding part of the example.