ZetCode

C# Base64

last modified November 15, 2026

This article shows how to encode and decode Base64 data in C#.

Base64 is a binary-to-text encoding that represents arbitrary bytes with 64 printable ASCII characters. It is defined in RFC 4648. Each Base64 character carries six bits, so three bytes (24 bits) are encoded as four characters. The encoded data is about a third larger than the original.

Base64 is used wherever binary data must travel through a channel designed for text: email attachments (MIME), images embedded in HTML and CSS as data URIs, binary fields in JSON and XML, JSON Web Tokens, and credentials in the HTTP Basic authentication header. Base64 is an encoding, not encryption; anyone can decode it.

The standard alphabet consists of the uppercase letters, the lowercase letters, the digits, and the + and / characters. The = character is used for padding.

Value Encoding  Value Encoding  Value Encoding  Value Encoding
 0 A            17 R            34 i            51 z
 1 B            18 S            35 j            52 0
 2 C            19 T            36 k            53 1
 3 D            20 U            37 l            54 2
 4 E            21 V            38 m            55 3
 5 F            22 W            39 n            56 4
 6 G            23 X            40 o            57 5
 7 H            24 Y            41 p            58 6
 8 I            25 Z            42 q            59 7
 9 J            26 a            43 r            60 8
10 K            27 b            44 s            61 9
11 L            28 c            45 t            62 +
12 M            29 d            46 u            63 /
13 N            30 e            47 v
14 O            31 f            48 w          (pad) =
15 P            32 g            49 x
16 Q            33 h            50 y

.NET provides Base64 support in several places:

API Description
Convert.ToBase64String Encodes a byte array or span to a Base64 string.
Convert.FromBase64String Decodes a Base64 string to a byte array.
Convert.TryToBase64Chars, Convert.TryFromBase64String Encode and decode into caller-provided spans without exceptions.
System.Buffers.Text.Base64 Span-based encoding to and from UTF-8 bytes; validation with IsValid.
System.Buffers.Text.Base64Url The URL-safe Base64 variant; available since .NET 9.
ToBase64Transform, FromBase64Transform Stream transformations for CryptoStream.

Convert.ToBase64String

The Convert.ToBase64String method encodes an array of bytes into a Base64 string. Text must first be converted to bytes with an encoding.

Program.cs
using System.Text;

string msg = "one \U0001F418 and three \U0001F40B";
byte[] data = Encoding.UTF8.GetBytes(msg);

string base64 = Convert.ToBase64String(data);

Console.WriteLine(msg);
Console.WriteLine(Convert.ToHexString(data));
Console.WriteLine(base64);

The example encodes a string containing two emoji characters.

string msg = "one \U0001F418 and three \U0001F40B";

The \U0001F418 and \U0001F40B escapes are the elephant and whale emoji.

byte[] data = Encoding.UTF8.GetBytes(msg);

We transform the string into a UTF-8 byte array. Each emoji takes four bytes.

string base64 = Convert.ToBase64String(data);

Then we encode the bytes into a Base64 string. For comparison, we also print the bytes in hexadecimal with Convert.ToHexString.

$ dotnet run
one 🐘 and three 🐋
6F6E6520F09F909820616E6420746872656520F09F908B
b25lIPCfkJggYW5kIHRocmVlIPCfkIs=

Convert.FromBase64String

The Convert.FromBase64String method decodes a Base64 string back into an array of bytes.

Program.cs
using System.Text;

string base64 = "b25lIPCfkJggYW5kIHRocmVlIPCfkIs=";
byte[] data = Convert.FromBase64String(base64);

string msg = Encoding.UTF8.GetString(data);

Console.WriteLine(Convert.ToHexString(data));
Console.WriteLine(msg);

try
{
    Convert.FromBase64String("b25lIPCfkJg*");
}
catch (FormatException ex)
{
    Console.WriteLine(ex.Message);
}

We decode the string from the previous example and then try to decode an invalid input.

byte[] data = Convert.FromBase64String(base64);

string msg = Encoding.UTF8.GetString(data);

The decoded bytes are turned back into text with the same encoding that was used to produce them.

Convert.FromBase64String("b25lIPCfkJg*");

The asterisk is not a Base64 character, so the method throws a FormatException.

$ dotnet run
6F6E6520F09F909820616E6420746872656520F09F908B
one 🐘 and three 🐋
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

How the encoding works

The encoder takes the input three bytes at a time and splits the 24 bits into four 6-bit groups. Each group is an index into the alphabet. When the input length is not a multiple of three, the last group is padded with = characters.

Program.cs
using System.Text;

string[] words = ["M", "Ma", "Man", "Many", "Manyo", "Manyon"];

foreach (string word in words)
{
    byte[] data = Encoding.ASCII.GetBytes(word);
    string encoded = Convert.ToBase64String(data);

    Console.WriteLine($"{word,-7} {data.Length} bytes -> {encoded,-8} {encoded.Length} chars");
}

Console.WriteLine("-----------------------");

byte[] bytes = Encoding.ASCII.GetBytes("Man");
string bits = string.Concat(bytes.Select(b => Convert.ToString(b, 2).PadLeft(8, '0')));

Console.WriteLine(string.Join(' ', bits.Chunk(8).Select(c => new string(c))));
Console.WriteLine(string.Join(' ', bits.Chunk(6).Select(c => new string(c))));

const string alphabet =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

var digits = bits.Chunk(6)
    .Select(group => Convert.ToInt32(new string(group), 2))
    .Select(val => $"{val}={alphabet[val]}");

Console.WriteLine(string.Join(' ', digits));

The program encodes words of growing length and then shows the encoding of Man step by step.

Console.WriteLine($"{word,-7} {data.Length} bytes -> {encoded,-8} {encoded.Length} chars");

One remaining byte produces two characters and ==, two remaining bytes produce three characters and =. The encoded length is always a multiple of four: 4×⌈n/3⌉.

string bits = string.Concat(bytes.Select(b => Convert.ToString(b, 2).PadLeft(8, '0')));

We join the binary representations of the three bytes into one string of 24 bits.

Console.WriteLine(string.Join(' ', bits.Chunk(8).Select(c => new string(c))));
Console.WriteLine(string.Join(' ', bits.Chunk(6).Select(c => new string(c))));

With Chunk, we print the bits split into the three original bytes and into the four 6-bit groups.

var digits = bits.Chunk(6)
    .Select(group => Convert.ToInt32(new string(group), 2))
    .Select(val => $"{val}={alphabet[val]}");

Each 6-bit group is converted to a number between 0 and 63 and looked up in the alphabet, giving TWFu.

$ dotnet run
M       1 bytes -> TQ==     4 chars
Ma      2 bytes -> TWE=     4 chars
Man     3 bytes -> TWFu     4 chars
Many    4 bytes -> TWFueQ== 8 chars
Manyo   5 bytes -> TWFueW8= 8 chars
Manyon  6 bytes -> TWFueW9u 8 chars
-----------------------
01001101 01100001 01101110
010011 010110 000101 101110
19=T 22=W 5=F 46=u

URL-safe Base64

The + and / characters have a special meaning in URLs and file names. The URL-safe variant from RFC 4648 replaces them with - and _ and usually omits the padding. It is used in JSON Web Tokens and in many web APIs. Since .NET 9, the Base64Url class implements it.

Program.cs
using System.Buffers.Text;
using System.Text;

byte[] data = Encoding.UTF8.GetBytes("<<subjects?>>");

string standard = Convert.ToBase64String(data);
string urlSafe = Base64Url.EncodeToString(data);

Console.WriteLine($"Standard: {standard}");
Console.WriteLine($"URL-safe: {urlSafe}");

byte[] decoded = Base64Url.DecodeFromChars(urlSafe);
Console.WriteLine($"Decoded: {Encoding.UTF8.GetString(decoded)}");

byte[] decoded2 = Base64Url.DecodeFromChars(urlSafe + "=");
Console.WriteLine($"Decoded with padding: {Encoding.UTF8.GetString(decoded2)}");

Console.WriteLine(Base64Url.IsValid(urlSafe));
Console.WriteLine(Base64Url.IsValid(standard));

The example encodes the same data with the standard and the URL-safe alphabet.

string urlSafe = Base64Url.EncodeToString(data);

Base64Url.EncodeToString produces - instead of + and drops the padding.

byte[] decoded = Base64Url.DecodeFromChars(urlSafe);

DecodeFromChars decodes the URL-safe string. Padding is optional; the decoder accepts the input with or without it.

Console.WriteLine(Base64Url.IsValid(urlSafe));
Console.WriteLine(Base64Url.IsValid(standard));

The standard encoding is not valid URL-safe Base64, because it contains the + character.

$ dotnet run
Standard: PDxzdWJqZWN0cz8+Pg==
URL-safe: PDxzdWJqZWN0cz8-Pg
Decoded: <<subjects?>>
Decoded with padding: <<subjects?>>
True
False

Line breaks

MIME requires that encoded lines are at most 76 characters long. The Base64FormattingOptions.InsertLineBreaks option inserts a line break after every 76 characters.

Program.cs
byte[] data = new byte[100];

for (int i = 0; i < data.Length; i++)
{
    data[i] = (byte)i;
}

string base64 = Convert.ToBase64String(data,
    Base64FormattingOptions.InsertLineBreaks);

Console.WriteLine(base64);

string[] lines = base64.Split("\r\n");
Console.WriteLine($"{lines.Length} lines, first has {lines[0].Length} chars");

byte[] decoded = Convert.FromBase64String(base64);
Console.WriteLine(decoded.SequenceEqual(data));

We encode 100 bytes with line breaks.

string base64 = Convert.ToBase64String(data,
    Base64FormattingOptions.InsertLineBreaks);

The 100 bytes give 136 characters, which are split into two lines.

string[] lines = base64.Split("\r\n");

The inserted line break is always \r\n, regardless of the operating system. Splitting on Environment.NewLine would leave a trailing \r in the lines on Linux and macOS.

byte[] decoded = Convert.FromBase64String(base64);

The decoder ignores whitespace, so the text can be decoded without removing the line breaks first.

$ dotnet run
AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4
OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiYw==
2 lines, first has 76 chars
True

Validating Base64

Instead of catching a FormatException, we can check the input with Base64.IsValid or decode it with Convert.TryFromBase64String, which returns false on failure.

Program.cs
using System.Buffers.Text;

string[] inputs = ["SGVsbG8=", "SGVsbG8", "SGVs bG8=", "SGVsbG8*", ""];

foreach (string input in inputs)
{
    bool valid = Base64.IsValid(input, out int length);
    Console.WriteLine($"{$"'{input}'",-12} valid: {valid,-5} bytes: {length}");
}

Console.WriteLine("-----------------------");

Span<byte> buffer = stackalloc byte[64];

if (Convert.TryFromBase64String("SGVsbG8=", buffer, out int written))
{
    Console.WriteLine($"decoded {written} bytes: {Convert.ToHexString(buffer[..written])}");
}

if (!Convert.TryFromBase64String("SGVsbG8", buffer, out _))
{
    Console.WriteLine("SGVsbG8 cannot be decoded");
}

The program validates several strings and decodes one of them into a stack-allocated buffer.

bool valid = Base64.IsValid(input, out int length);

Base64.IsValid also returns the number of bytes the input decodes to. Whitespace is allowed, a missing padding is not. An empty string is valid Base64 for zero bytes.

if (Convert.TryFromBase64String("SGVsbG8=", buffer, out int written))

TryFromBase64String writes the decoded bytes into a span and reports how many bytes it wrote. It returns false for invalid input or when the buffer is too small.

$ dotnet run
'SGVsbG8='   valid: True  bytes: 5
'SGVsbG8'    valid: False bytes: 0
'SGVs bG8='  valid: True  bytes: 5
'SGVsbG8*'   valid: False bytes: 0
''           valid: True  bytes: 0
-----------------------
decoded 5 bytes: 48656C6C6F
SGVsbG8 cannot be decoded

Span-based encoding

The System.Buffers.Text.Base64 class encodes and decodes directly between byte spans. The Base64 text is represented as UTF-8 bytes, which avoids string allocations when the data is read from or written to a network stream or a file.

Program.cs
using System.Buffers;
using System.Buffers.Text;
using System.Text;

byte[] src = Encoding.UTF8.GetBytes("one \U0001F418 and three \U0001F40B");

byte[] encoded = new byte[Base64.GetMaxEncodedToUtf8Length(src.Length)];
OperationStatus status = Base64.EncodeToUtf8(src, encoded,
    out int consumed, out int written);

Console.WriteLine($"{status}: {consumed} bytes in, {written} bytes out");
Console.WriteLine(Encoding.ASCII.GetString(encoded, 0, written));

byte[] decoded = new byte[Base64.GetMaxDecodedFromUtf8Length(written)];
status = Base64.DecodeFromUtf8(encoded.AsSpan(0, written), decoded,
    out consumed, out written);

Console.WriteLine($"{status}: {consumed} bytes in, {written} bytes out");
Console.WriteLine(Encoding.UTF8.GetString(decoded, 0, written));

Console.WriteLine("-----------------------");

Span<char> chars = stackalloc char[16];

if (Convert.TryToBase64Chars("Hello"u8, chars, out int charsWritten))
{
    Console.WriteLine(chars[..charsWritten].ToString());
}

The example encodes and decodes the emoji message with byte spans.

byte[] encoded = new byte[Base64.GetMaxEncodedToUtf8Length(src.Length)];
OperationStatus status = Base64.EncodeToUtf8(src, encoded,
    out int consumed, out int written);

GetMaxEncodedToUtf8Length computes the size of the destination buffer. EncodeToUtf8 returns an OperationStatus and reports the number of bytes consumed and written. Besides Done, the status can say that the destination is too small or that the input is incomplete, which allows encoding data in chunks.

status = Base64.DecodeFromUtf8(encoded.AsSpan(0, written), decoded,
    out consumed, out written);

DecodeFromUtf8 works the other way round. We pass only the written part of the buffer.

if (Convert.TryToBase64Chars("Hello"u8, chars, out int charsWritten))

Convert.TryToBase64Chars encodes into a span of characters. The u8 suffix creates a UTF-8 byte span from a string literal.

$ dotnet run
Done: 23 bytes in, 32 bytes out
b25lIPCfkJggYW5kIHRocmVlIPCfkIs=
Done: 32 bytes in, 23 bytes out
one 🐘 and three 🐋
-----------------------
SGVsbG8=

Data URIs

A data URI embeds a file directly into an HTML or CSS document. It consists of the data: scheme, the media type, the ;base64 marker, and the encoded data.

Program.cs
using System.Text;

byte[] gif = Convert.FromHexString(
    "47494638396101000100800000FF000000000021F90400000000002C0000000001000100000202440100");
File.WriteAllBytes("dot.gif", gif);

byte[] imageBytes = File.ReadAllBytes("dot.gif");
string dataUri = $"data:image/gif;base64,{Convert.ToBase64String(imageBytes)}";

Console.WriteLine($"{imageBytes.Length} bytes");
Console.WriteLine(dataUri);

string html = $"""
<!DOCTYPE html>
<html>
<body>
<img src="{dataUri}" width="50" height="50" alt="red dot">
</body>
</html>
""";

File.WriteAllText("index.html", html, Encoding.UTF8);
Console.WriteLine("index.html written");

The program creates a small GIF image, encodes it, and embeds it into an HTML page.

byte[] gif = Convert.FromHexString(
    "47494638396101000100800000FF000000000021F90400000000002C0000000001000100000202440100");
File.WriteAllBytes("dot.gif", gif);

To keep the example self-contained, we write a 42-byte GIF image with a single red pixel. In practice, the image would already exist.

byte[] imageBytes = File.ReadAllBytes("dot.gif");
string dataUri = $"data:image/gif;base64,{Convert.ToBase64String(imageBytes)}";

We read the file into a byte array and build the data URI.

<img src="{dataUri}" width="50" height="50" alt="red dot">

The URI is used as the src of an image in a raw string literal. The browser shows a red square without loading any other file. Data URIs suit small images; large files make the page bigger by a third and cannot be cached separately.

$ dotnet run
42 bytes
data:image/gif;base64,R0lGODlhAQABAIAAAP8AAAAAACH5BAAAAAAALAAAAAABAAEAAAICRAEA
index.html written

Encoding streams

Convert.ToBase64String needs the whole input in memory. For large files, we can encode a stream with CryptoStream and the ToBase64Transform and FromBase64Transform classes.

Program.cs
using System.Security.Cryptography;

byte[] data = new byte[1_000_000];
Random.Shared.NextBytes(data);
File.WriteAllBytes("data.bin", data);

using (FileStream input = File.OpenRead("data.bin"))
using (FileStream output = File.Create("data.b64"))
using (var b64 = new CryptoStream(output, new ToBase64Transform(),
    CryptoStreamMode.Write))
{
    input.CopyTo(b64);
}

Console.WriteLine($"data.bin: {new FileInfo("data.bin").Length} bytes");
Console.WriteLine($"data.b64: {new FileInfo("data.b64").Length} bytes");

using (FileStream input = File.OpenRead("data.b64"))
using (var b64 = new CryptoStream(input, new FromBase64Transform(),
    CryptoStreamMode.Read))
using (FileStream output = File.Create("data2.bin"))
{
    b64.CopyTo(output);
}

byte[] restored = File.ReadAllBytes("data2.bin");
Console.WriteLine(restored.AsSpan().SequenceEqual(data));

The example encodes a one-megabyte file to Base64 and decodes it again, working in small blocks.

using (var b64 = new CryptoStream(output, new ToBase64Transform(),
    CryptoStreamMode.Write))
{
    input.CopyTo(b64);
}

The CryptoStream wraps the output file. All bytes written to it pass through the ToBase64Transform. Disposing the stream flushes the final block with the padding.

using (var b64 = new CryptoStream(input, new FromBase64Transform(),
    CryptoStreamMode.Read))

For decoding, the CryptoStream wraps the input file in read mode. The 1000000 bytes became 1333336 characters, four for every three bytes.

$ dotnet run
data.bin: 1000000 bytes
data.b64: 1333336 bytes
True

Basic authentication

HTTP Basic authentication sends the user name and password joined with a colon and encoded with Base64 in the Authorization header.

Program.cs
using System.Net.Http.Headers;
using System.Text;

string user = "admin";
string password = "s3cret:pass";

string credentials = Convert.ToBase64String(
    Encoding.UTF8.GetBytes($"{user}:{password}"));

var header = new AuthenticationHeaderValue("Basic", credentials);
Console.WriteLine($"Authorization: {header}");

string decoded = Encoding.UTF8.GetString(
    Convert.FromBase64String(header.Parameter!));

int idx = decoded.IndexOf(':');
Console.WriteLine($"user: {decoded[..idx]}, password: {decoded[(idx + 1)..]}");

The program builds the header value and decodes it again.

string credentials = Convert.ToBase64String(
    Encoding.UTF8.GetBytes($"{user}:{password}"));

var header = new AuthenticationHeaderValue("Basic", credentials);

The encoded credentials are wrapped in an AuthenticationHeaderValue, which we would assign to HttpClient.DefaultRequestHeaders.Authorization.

int idx = decoded.IndexOf(':');

A server splits the decoded text at the first colon, because a password may contain colons, while the user name may not. Since anyone can decode the header, Basic authentication must only be used over HTTPS.

$ dotnet run
Authorization: Basic YWRtaW46czNjcmV0OnBhc3M=
user: admin, password: s3cret:pass

Extension members

With the C# 14 extension blocks, we can add Base64 helpers to the string type.

Program.cs
using System.Text;

string msg = "one \U0001F418 and three \U0001F40B";

string base64 = msg.ToBase64();
string msg2 = base64.FromBase64();

Console.WriteLine(base64);
Console.WriteLine(msg2);
Console.WriteLine(msg == msg2);

static class Base64Extensions
{
    extension(string s)
    {
        public string ToBase64() =>
            Convert.ToBase64String(Encoding.UTF8.GetBytes(s));

        public string FromBase64() =>
            Encoding.UTF8.GetString(Convert.FromBase64String(s));
    }
}

The example defines the ToBase64 and FromBase64 extension methods.

extension(string s)
{

The extension block declares the receiver once; all members inside it extend string. The block must be placed in a non-generic static class.

public string ToBase64() =>
    Convert.ToBase64String(Encoding.UTF8.GetBytes(s));

The methods use UTF-8 for the conversion between text and bytes, and are called like instance methods on strings.

$ dotnet run
b25lIPCfkJggYW5kIHRocmVlIPCfkIs=
one 🐘 and three 🐋
True

Source

Convert.ToBase64String method - .NET API

Base64 class - .NET API

Base64Url class - .NET API

In this article we have encoded and decoded Base64 data in C#. See also the Encoding, byte array to hex string, Convert, HttpClient, and extension method tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.