Base64 Encode & Decode in C#

Encode or decode below — it runs locally in your browser — then grab the canonical C# code. .NET provides Convert.ToBase64String() and Convert.FromBase64String(), which work on byte[], so you go through Encoding.UTF8 to convert text to and from bytes.

INPUT
OUTPUT
Type or paste to encode / decode

Encode and decode a string

The key pattern is string → Encoding.UTF8.GetBytes() → Convert.ToBase64String() → string:

using System;
using System.Text;

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

// Decode
string decoded = Encoding.UTF8.GetString(Convert.FromBase64String(encoded));
Console.WriteLine(decoded);  // Hello, world!

Tip: Convert.ToBase64String works on a byte[], not a string — always go through Encoding.UTF8 to turn text into bytes (and back) so encoding is explicit and platform-independent.

URL-safe Base64

For JWTs, URLs, and filenames, use the URL-safe alphabet (- and _ instead of + and /):

// .NET 9+ has a dedicated Base64Url helper
using System.Buffers.Text;

string encoded = Base64Url.EncodeToString(Encoding.UTF8.GetBytes("Hello, world!"));

// Earlier .NET — adapt the standard alphabet by hand
public static string ToBase64Url(byte[] data)
{
    return Convert.ToBase64String(data)
        .Replace('+', '-')
        .Replace('/', '_')
        .TrimEnd('=');
}

Encode a file / span APIs

using System;
using System.IO;

// Encode a file to a Base64 string
string encoded = Convert.ToBase64String(File.ReadAllBytes("image.png"));

// As a data URI for HTML/CSS:
string dataUri = "data:image/png;base64," + encoded;

// Zero-allocation: encode straight into a stack buffer
byte[] bytes = Encoding.UTF8.GetBytes("Hello, world!");
Span<char> buffer = stackalloc char[((bytes.Length + 2) / 3) * 4];
Convert.TryToBase64Chars(bytes, buffer, out int written);

Frequently asked questions

How do I Base64 encode a string in C#?

Convert the string to bytes, then encode: Convert.ToBase64String(Encoding.UTF8.GetBytes("Hello, world!")) returns "SGVsbG8sIHdvcmxkIQ==".

How do I Base64 decode in C#?

Convert.FromBase64String(s) returns the byte[]; wrap it with Encoding.UTF8.GetString(...) for a string.

How do I do URL-safe Base64?

Use Base64Url.EncodeToString() on .NET 9+, or .Replace('+','-').Replace('/','_').TrimEnd('=') on the standard output for older versions.

Why do I get a FormatException from Convert.FromBase64String?

The input must be valid, padded Base64 whose length is a multiple of 4. Restore padding and convert -/_ back to +// before decoding.

Need image, file, or URL-safe modes?

The main base64.dev tool handles text, images, files, and URL-safe Base64 with auto-detect.

Open base64.dev →