.NET exposes Base64 through the static Convert class, the high-performance System.Buffers.Text.Base64 API, and since .NET 9 a dedicated Base64Url class.
Strings
using System.Text;
string b64 = Convert.ToBase64String(Encoding.UTF8.GetBytes("Grüße 👋"));
string text = Encoding.UTF8.GetString(Convert.FromBase64String(b64));
Safe decoding without exceptions
Convert.FromBase64String throws FormatException for invalid input. Use TryFromBase64String with a buffer instead:
Span<byte> buffer = new byte[input.Length * 3 / 4];
if (Convert.TryFromBase64String(input, buffer, out int written))
{
var data = buffer[..written];
}
FromBase64String ignores whitespace (spaces, tabs, CR, LF) but rejects any other character, including the URL-safe - and _.
Base64URL
// .NET 9+
using System.Buffers.Text;
string token = Base64Url.EncodeToString(bytes);
byte[] back = Base64Url.DecodeFromChars(token);
// Older versions
static string ToBase64Url(byte[] b) =>
Convert.ToBase64String(b).TrimEnd('=').Replace('+', '-').Replace('/', '_');
ASP.NET Core also offers WebEncoders.Base64UrlEncode in Microsoft.AspNetCore.WebUtilities.
Line breaks
Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks); // 76 chars per line
Files and streams
string b64 = Convert.ToBase64String(await File.ReadAllBytesAsync("photo.jpg"));
await File.WriteAllBytesAsync("copy.jpg", Convert.FromBase64String(b64));
// Streaming:
using var input = File.OpenRead("big.bin");
using var output = File.Create("big.b64");
using var transform = new CryptoStream(output, new ToBase64Transform(), CryptoStreamMode.Write);
await input.CopyToAsync(transform);
Image to data URI (ASP.NET)
var src = $"data:image/png;base64,{Convert.ToBase64String(pngBytes)}";
Verify results with the Base64 decoder.
Comments (0)
Questions, ideas or a bug in “Base64 in C# and .NET”? Leave a comment, rate the tool, or reply to others.
No comments yet. Be the first to share your feedback!