Base64 in C#

Last updated: February 2026

How to encode and decode Base64 in C# and .NET using the Convert class

How Do You Encode a String to Base64 in C#?

Use Convert.ToBase64String() combined with Encoding.UTF8.GetBytes() to encode a string to Base64. The GetBytes() call converts the string into a UTF-8 byte array, and ToBase64String() produces the Base64-encoded output. This method has been available since .NET Framework 1.0 and works across all .NET versions.

using System;
using System.Text;

string original = "Hello, World!";
byte[] bytes = Encoding.UTF8.GetBytes(original);
string encoded = Convert.ToBase64String(bytes);
Console.WriteLine(encoded); // SGVsbG8sIFdvcmxkIQ==

Always specify the character encoding explicitly using Encoding.UTF8 rather than Encoding.Default to ensure consistent behavior across platforms. The returned string uses the standard Base64 alphabet (A-Z, a-z, 0-9, +, /) with = padding. For a browser-based alternative, use the Base64 text encoder.

How Do You Decode Base64 in C#?

Use Convert.FromBase64String() to convert a Base64 string back to a byte array, then Encoding.UTF8.GetString() to reconstruct the original string. The FromBase64String() method validates the input and throws FormatException if the string contains invalid Base64 characters or has incorrect padding.

using System;
using System.Text;

string encoded = "SGVsbG8sIFdvcmxkIQ==";
byte[] bytes = Convert.FromBase64String(encoded);
string decoded = Encoding.UTF8.GetString(bytes);
Console.WriteLine(decoded); // Hello, World!

Validate Base64 input before decoding in production code. The decoder rejects whitespace characters other than spaces, tabs, and newlines. To decode Base64 strings directly in your browser, use the Base64 text decoder.

How Do You Encode a File to Base64 in C#?

Read the file into a byte array using File.ReadAllBytes(), then pass the array to Convert.ToBase64String(). This approach loads the entire file into memory and works for files that fit within available RAM.

using System;
using System.IO;

byte[] fileBytes = File.ReadAllBytes("image.png");
string encoded = Convert.ToBase64String(fileBytes);

// Create a data URI for HTML embedding
string dataUri = "data:image/png;base64," + encoded;
Console.WriteLine(dataUri);

For images, prepend the appropriate MIME type to create a data URI. The Base64 file encoder performs the same operation in your browser without uploading the file. To decode back to a file, use File.WriteAllBytes(path, Convert.FromBase64String(base64)).

What Base64 Methods Does .NET Provide?

The System.Convert class provides 5 Base64-related methods. .NET Core 2.1 added TryFromBase64String() for non-throwing validation. The Base64FormattingOptions enum controls whether the output includes line breaks for MIME compatibility.

MethodReturnsDescription
ToBase64String(byte[])stringEncode byte array to Base64 string
FromBase64String(string)byte[]Decode Base64 string to byte array
TryFromBase64String(string, Span<byte>, out int)boolTry to decode without throwing (.NET Core 2.1+)
ToBase64CharArray(byte[], int, int, char[], int)intEncode into a char array, returns length
ToBase64String(byte[], Base64FormattingOptions)stringEncode with optional line breaks every 76 chars

The Base64FormattingOptions.InsertLineBreaks flag inserts CRLF every 76 characters, matching MIME format (RFC 2045). The default Base64FormattingOptions.None produces a continuous string with no line breaks. For a complete reference on the Base64 alphabet, see the Base64 character table.

How Do You Use Base64 with Streams in C#?

Use CryptoStream with ToBase64Transform or FromBase64Transform from the System.Security.Cryptography namespace to process large files without loading them entirely into memory. The transform classes process data in fixed-size blocks through a stream pipeline.

using System.IO;
using System.Security.Cryptography;

// Encode a large file to Base64 using streams
using (var input = File.OpenRead("large-file.bin"))
using (var output = File.Create("large-file.b64"))
using (var transform = new ToBase64Transform())
using (var cryptoStream = new CryptoStream(output, transform, CryptoStreamMode.Write))
{
    input.CopyTo(cryptoStream);
}

// Decode a Base64 file using streams
using (var input = File.OpenRead("large-file.b64"))
using (var output = File.Create("decoded-file.bin"))
using (var transform = new FromBase64Transform())
using (var cryptoStream = new CryptoStream(input, transform, CryptoStreamMode.Read))
{
    cryptoStream.CopyTo(output);
}

The ToBase64Transform processes 3 input bytes at a time and outputs 4 Base64 characters. The FromBase64Transform reverses this operation. This approach handles files of any size because only a small buffer resides in memory. Learn more about Base64 encoding fundamentals in the What is Base64 guide.

How Do You Create URL-Safe Base64 in C#?

Replace + with - and / with _ in the standard Base64 output, then optionally trim trailing = padding. In ASP.NET Core, use the built-in WebEncoders.Base64UrlEncode() method from Microsoft.AspNetCore.WebUtilities which handles the URL-safe alphabet automatically.

using System;
using System.Text;

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

// Manual URL-safe encoding
string base64 = Convert.ToBase64String(data);
string urlSafe = base64.Replace('+', '-').Replace('/', '_').TrimEnd('=');
Console.WriteLine(urlSafe); // c3ViamVjdHM_YWJjZA

// ASP.NET Core: using Microsoft.AspNetCore.WebUtilities
// string urlSafe = WebEncoders.Base64UrlEncode(data);

URL-safe Base64 prevents encoding conflicts when the string appears in query parameters or URL paths. This variant follows RFC 4648 Section 5. The URL-safe Base64 tool provides browser-based encoding with the same alphabet.

How Do You Handle Base64 Errors in C#?

Convert.FromBase64String() throws System.FormatException when the input is invalid. Common causes include non-Base64 characters, incorrect string length, and malformed padding. Use Convert.TryFromBase64String() in .NET Core 2.1+ for non-throwing validation.

using System;

// Approach 1: Try-catch (all .NET versions)
try
{
    byte[] decoded = Convert.FromBase64String(input);
}
catch (FormatException ex)
{
    Console.WriteLine($"Invalid Base64: {ex.Message}");
}

// Approach 2: TryFromBase64String (.NET Core 2.1+)
Span<byte> buffer = new byte[input.Length];
if (Convert.TryFromBase64String(input, buffer, out int bytesWritten))
{
    // Valid Base64 - use buffer[..bytesWritten]
}
else
{
    Console.WriteLine("Invalid Base64 input");
}

The TryFromBase64String() method avoids the performance overhead of exception handling in validation scenarios. For quick browser-based validation, use the Base64 validator tool.

Frequently Asked Questions

Does C# have built-in Base64 support?

Yes. The System.Convert class provides Convert.ToBase64String() and Convert.FromBase64String() for Base64 encoding and decoding. These methods have been available since .NET Framework 1.0 and are included in all .NET versions including .NET Core and .NET 5+. No third-party packages are required.

How do you validate a Base64 string in C#?

Use Convert.TryFromBase64String() available in .NET Core 2.1 and later. This method returns a bool indicating whether the input is valid Base64 without throwing an exception. For older .NET Framework versions, wrap Convert.FromBase64String() in a try-catch block and handle FormatException.

How do you handle large files with Base64 in C#?

Use CryptoStream with ToBase64Transform or FromBase64Transform from the System.Security.Cryptography namespace. These classes process data in chunks through a stream pipeline, avoiding loading the entire file into memory. This approach handles files of any size within available disk space.

How do you create URL-safe Base64 in C#?

Replace + with - and / with _ in the output of Convert.ToBase64String(), then optionally remove trailing = padding. In ASP.NET Core, use Microsoft.AspNetCore.WebUtilities.WebEncoders.Base64UrlEncode() which handles the URL-safe alphabet automatically following RFC 4648 Section 5.

What exception does C# throw for invalid Base64 input?

Convert.FromBase64String() throws System.FormatException when the input contains invalid characters, has incorrect length, or includes invalid padding. The exception message specifies the nature of the error. Use Convert.TryFromBase64String() in .NET Core 2.1+ to avoid exceptions during validation.

Related Base64 Tools and Guides