Base64 encode/decode · Guide

Base64 to Text C#: Convert.FromBase64String Explained

.NET puts Base64 on the `Convert` class rather than in a crypto namespace, which is the right place for it — it is an encoding, not a security feature. The details worth knowing are encoding choice and how to handle input you do not control.

The basic conversion

Two steps: Base64 to bytes, then bytes to a string with an explicit encoding:

C#
using System;
using System.Text;

byte[] bytes = Convert.FromBase64String("Y2Fmw6k=");
string text  = Encoding.UTF8.GetString(bytes);      // "café"

// the other direction
string b64 = Convert.ToBase64String(Encoding.UTF8.GetBytes("café"));

Specify Encoding.UTF8 rather than Encoding.Default. .NET strings are UTF-16 internally, so Encoding.Unicode produces a completely different Base64 string — a frequent cause of values that will not match another system.

Untrusted input

FromBase64String throws FormatException on bad padding or invalid characters. For anything user-supplied, use the non-throwing variant:

C#
Span<byte> buffer = new byte[value.Length * 3 / 4];
if (Convert.TryFromBase64String(value, buffer, out int written))
{
    var text = Encoding.UTF8.GetString(buffer[..written]);
}

It also avoids the exception cost in a hot path, which matters if you are validating many tokens.

base64url and line breaks

Convert handles only the standard alphabet. For JWT segments, translate first, or use Base64Url from .NET 9 where available:

C#
static byte[] FromBase64Url(string s)
{
    s = s.Replace('-', '+').Replace('_', '/');
    return Convert.FromBase64String(s.PadRight(s.Length + (4 - s.Length % 4) % 4, '='));
}

Convert.ToBase64String accepts Base64FormattingOptions.InsertLineBreaks if you need MIME-style wrapping — the default is a single line, which is usually what you want.

Frequently asked questions

Why does my C# Base64 differ from another system?

Encoding. .NET strings are UTF-16; convert with Encoding.UTF8.GetBytes before encoding.

How do I avoid FormatException?

Use Convert.TryFromBase64String, which returns false instead of throwing.

Does Convert handle base64url?

Not directly before .NET 9. Replace the two characters and pad manually.

Ready to try it?

Open the free browser-based Base64 encode/decode and apply what you just read — no sign-up, runs locally.

Open the Base64 encode/decode tool