Decoding Base64 in C# and .NET
In the C# and .NET ecosystem, Base64 operations are a core part of the system infrastructure, heavily utilized in cryptography, web APIs, and configuration files. .NET provides robust, high-performance methods for translating between text and binary arrays.
The Convert Class
The primary entry point for Base64 operations in C# is the static System.Convert class. Similar to Java, C# strictly separates strings (UTF-16 characters) from byte arrays. You must define the encoding when translating.
Basic Base64 Decoding
To decode a Base64 string into a readable C# string, you first convert it into a byte array, and then use System.Text.Encoding to parse those bytes.
using System;
using System.Text;
class Program
{
static void Main()
{
string base64String = "SGVsbG8sIC5ORVQgQ29yZSE=";
// 1. Decode to byte array
byte[] bytes = Convert.FromBase64String(base64String);
// 2. Parse bytes to a UTF-8 string
string decodedText = Encoding.UTF8.GetString(bytes);
Console.WriteLine(decodedText);
// Output: Hello, .NET Core!
}
}
Basic Base64 Encoding
Encoding reverses the flow: Extract the UTF-8 bytes from the string, then convert the array to Base64.
string originalText = "Secure Data 123";
byte[] textBytes = Encoding.UTF8.GetBytes(originalText);
string encodedText = Convert.ToBase64String(textBytes);
Console.WriteLine(encodedText);
// Output: U2VjdXJlIERhdGEgMTIz
Handling URL-Safe Base64 in ASP.NET
If you are building an ASP.NET Core web application, you frequently need to encode data safely for URLs (such as passing a token in a query string). While you can manually use Replace('+', '-'), ASP.NET provides built-in utilities specifically for this via the Microsoft.AspNetCore.WebUtilities namespace.
using Microsoft.AspNetCore.WebUtilities;
using System.Text;
// Encoding to URL Safe
byte[] bytes = Encoding.UTF8.GetBytes("Testing URL Safe!");
string urlSafe = WebEncoders.Base64UrlEncode(bytes);
// Decoding from URL Safe
byte[] decodedBytes = WebEncoders.Base64UrlDecode(urlSafe);
string result = Encoding.UTF8.GetString(decodedBytes);
This utility natively handles the character replacements and padding corrections required for JWTs and OAuth tokens.
High Performance Base64 with Span<T>
In high-performance .NET applications, allocating a new byte array for every Base64 conversion can cause excessive Garbage Collection (GC) pressure. Modern .NET addresses this by supporting Base64 operations directly on Span<T> and Memory<T> types.
The System.Buffers.Text.Base64 class provides allocation-free encoding and decoding.
using System;
using System.Buffers.Text;
using System.Text;
public class PerfExample
{
public void DecodeAllocationFree(ReadOnlySpan base64Bytes)
{
// Allocate a span on the stack (fast, no GC pressure)
Span decodedBytes = stackalloc byte[base64Bytes.Length];
// Decode directly into the span
OperationStatus status = Base64.DecodeFromUtf8(base64Bytes, decodedBytes, out int bytesConsumed, out int bytesWritten);
if (status == OperationStatus.Done)
{
// Slice the span to the actual written length
var actualData = decodedBytes.Slice(0, bytesWritten);
Console.WriteLine(Encoding.UTF8.GetString(actualData));
}
}
}
Exception Handling
When calling Convert.FromBase64String(), be prepared to catch a FormatException. This occurs if:
- The string length (excluding whitespace) is not a multiple of 4.
- The string contains invalid characters (like hyphens or underscores if it is a URL-safe string).
Conclusion
.NET provides a highly mature ecosystem for handling Base64. For simple scripts and basic web APIs, Convert.FromBase64String is perfectly sufficient. For extreme performance requirements, the modern System.Buffers.Text.Base64 APIs allow you to process millions of strings with zero allocations.
To inspect your .NET Base64 outputs, copy your strings into our Base64 Decoder tool.