How to achieve Base64 URL safe encoding in C#?

It is common to simply swap alphabet for use in urls, so that no %-encoding is necessary; only 3 of the 65 characters are problematic – +, / and =. the most common replacements are - in place of + and _ in place of /. As for the padding: just remove it (the =); you can infer the amount of padding needed. At the other end: just reverse the process:

string returnValue = System.Convert.ToBase64String(toEncodeAsBytes)
        .TrimEnd(padding).Replace('+', '-').Replace("https://stackoverflow.com/", '_');

with:

static readonly char[] padding = { '=' };

and to reverse:

string incoming = returnValue
    .Replace('_', "https://stackoverflow.com/").Replace('-', '+');
switch(returnValue.Length % 4) {
    case 2: incoming += "=="; break;
    case 3: incoming += "="; break;
}
byte[] bytes = Convert.FromBase64String(incoming);
string originalText = Encoding.ASCII.GetString(bytes);

The interesting question, however, is: is this the same approach that the “common codec library” uses? It would certainly be a reasonable first thing to test – this is a pretty common approach.

Leave a Comment