In C#, Convert.TryFromBase64String attempts to decode Base64 text into a destination byte buffer.
It returns false for invalid text or a too-small buffer instead of throwing FormatException.
This is a static member of System.Convert. You call it with the type name, such as Convert.TryFromBase64String(...). Convert is the everyday API for converting between common CLR types in C#.
Syntax
Pass the Base64 string and a destination byte span.
C#
Span<byte> dest = stackalloc byte[8];
bool ok = Convert.TryFromBase64String("AQID", dest, out int written);
Call
What it does
Convert.TryFromBase64String(text, dest, out written)
true when decode succeeds.
Newer .NET API. On older runtimes use FromBase64String inside try/catch.
Library declarations
C#
public static bool TryFromBase64String(string s, Span<byte> bytes, out int bytesWritten);
Parameters
Parameter
Description
s
Required. Base64 text.
bytes
Required. Destination buffer.
bytesWritten
Out. Bytes written on success.
Return Value
Return Value
Description
true
Decode succeeded.
false
Invalid Base64 or buffer too small.
C# Examples
Example 1 — Decode Valid Base64
Try-decode AQID into a stack buffer.
C#
using System;
class Program {
static void Main() {
Span<byte> dest = stackalloc byte[8];
bool ok = Convert.TryFromBase64String("AQID", dest, out int written);
Console.WriteLine(ok);
Console.WriteLine(string.Join(",", dest.Slice(0, written).ToArray()));
}
}
Output
True
1,2,3
How It Works
Valid text. AQID is well-formed Base64.
ok true. Decode filled the span.
written slice. Print only produced bytes.
1,2,3. Expected payload.
Example 2 — False on Garbage
Show false for illegal Base64 characters.
C#
using System;
class Program {
static void Main() {
Span<byte> dest = stackalloc byte[8];
bool ok = Convert.TryFromBase64String("****", dest, out int written);
Console.WriteLine(ok);
Console.WriteLine(written);
}
}
Output
False
0
How It Works
Illegal stars. Not Base64 alphabet.
false. No exception thrown.
written 0. Treat output as unused.
Safer UX. Good for validating user paste.
Example 3 — Contrast with FromBase64String
Catch FormatException from the throwing API.
C#
using System;
class Program {
static void Main() {
Span<byte> dest = stackalloc byte[8];
Console.WriteLine(Convert.TryFromBase64String("AQID", dest, out _));
try {
Convert.FromBase64String("****");
} catch (FormatException) {
Console.WriteLine("threw");
}
}
}
Output
True
threw
How It Works
Try succeeds. AQID decodes with true.
Throwing API. FromBase64String rejects ****.
FormatException. Catch prints threw.
Pick Try. When bad input is expected.
Frequently Asked Questions
Use Try for untrusted input; From when failure should be exceptional.