DevToolsForYou

Base64 Encoder and Decoder in C# / .NET — Code Examples

Base64 Encoder and Decoder in C# / .NETUse the online tool →

Base64 encoding converts binary or text data into a 64-character ASCII alphabet so it can be safely transmitted over text-only channels. Here is how to encode and decode Base64 in each language using only the standard library.

C# provides Convert.ToBase64String and Convert.FromBase64String in the BCL. For URL-safe Base64, replace non-URL-safe characters after encoding.

C# / .NET
using System;
using System.Text;

// Encode
byte[] bytes = Encoding.UTF8.GetBytes("Hello, world!");
string encoded = Convert.ToBase64String(bytes);
Console.WriteLine(encoded); // SGVsbG8sIHdvcmxkIQ==

// Decode
byte[] decodedBytes = Convert.FromBase64String("SGVsbG8sIHdvcmxkIQ==");
string decoded = Encoding.UTF8.GetString(decodedBytes);
Console.WriteLine(decoded); // Hello, world!

// URL-safe Base64 (replace + with - and / with _, strip =)
string urlSafe = encoded.Replace('+', '-').Replace('/', '_').TrimEnd('=');

// Decode URL-safe Base64 (restore padding before decoding)
string padded = urlSafe.Replace('-', '+').Replace('_', '/');
int rem = padded.Length % 4;
if (rem > 0) padded = padded.PadRight(padded.Length + (4 - rem), '=');
string urlDecoded = Encoding.UTF8.GetString(Convert.FromBase64String(padded));

// .NET 8+: cleaner URL-safe API
// string urlSafe = System.Buffers.Text.Base64Url.EncodeToString(bytes);
// byte[] back    = System.Buffers.Text.Base64Url.DecodeFromChars(urlSafe);
Notes & gotchas
  • Convert.FromBase64String throws FormatException on invalid input — wrap in try/catch in production code.
  • For .NET 8+, System.Buffers.Text.Base64Url provides a cleaner, allocation-friendly URL-safe API.
  • Always specify Encoding.UTF8 explicitly when converting strings to bytes to avoid platform encoding surprises.
Try it in your browser

Need to base64 encode/decode without writing code? The Base64 Encoder and Decoder runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open Base64 Encode/Decode
Base64 Encoder and Decoder in other languages