In C#, Convert.TryFromBase64Chars decodes a ReadOnlySpan<char> of Base64 text into a byte destination.
Returns false instead of throwing when the text is invalid or the buffer is too small.
This is a static member of System.Convert. You call it with the type name, such as Convert.TryFromBase64Chars(...). Convert is the everyday API for converting between common CLR types in C#.
Syntax
Pass source chars and a destination byte span.
C#
ReadOnlySpan<char> text = "AQID";
Span<byte> dest = stackalloc byte[8];
bool ok = Convert.TryFromBase64Chars(text, dest, out int written);
Call
What it does
Convert.TryFromBase64Chars(text, dest, out written)
true when decode succeeds.
Sibling of TryFromBase64String for char spans. Modern .NET required.
Library declarations
C#
public static bool TryFromBase64Chars(ReadOnlySpan<char> chars,
Span<byte> bytes, out int bytesWritten);
Parameters
Parameter
Description
chars
Required. Base64 characters.
bytes
Required. Destination buffer.
bytesWritten
Out. Bytes written on success.
Return Value
Return Value
Description
true
Decode succeeded.
false
Invalid input or buffer too small.
C# Examples
Example 1 — Decode a Char Span
Try-decode AQID from a string as span.
C#
using System;
class Program {
static void Main() {
ReadOnlySpan<char> text = "AQID";
Span<byte> dest = stackalloc byte[8];
bool ok = Convert.TryFromBase64Chars(text, dest, out int written);
Console.WriteLine(ok);
Console.WriteLine(string.Join(",", dest.Slice(0, written).ToArray()));
}
}
No string decode API required. Chars go straight in.
Example 2 — False for Bad Alphabet
Reject non-Base64 characters softly.
C#
using System;
class Program {
static void Main() {
Span<byte> dest = stackalloc byte[8];
bool ok = Convert.TryFromBase64Chars("@@@@", dest, out int written);
Console.WriteLine(ok);
Console.WriteLine(written);
}
}
Output
False
0
How It Works
@@@@. Outside the Base64 alphabet.
false result. Soft failure path.
written 0. Ignore destination contents.
No throw. Unlike FromBase64CharArray.
Example 3 — Decode From String Slice
Use AsSpan to decode a substring region.
C#
using System;
class Program {
static void Main() {
string raw = "xxAQIDyy";
Span<byte> dest = stackalloc byte[8];
bool ok = Convert.TryFromBase64Chars(raw.AsSpan(2, 4), dest, out int written);
Console.WriteLine(ok);
Console.WriteLine(string.Join(",", dest.Slice(0, written).ToArray()));
}
}
Output
True
1,2,3
How It Works
Embedded text. AQID sits inside a larger string.
AsSpan(2,4). Selects only the Base64 part.
Decode ok. Same bytes as a plain AQID.
No substring alloc. Span avoids new string().
Frequently Asked Questions
Chars takes a char span; String takes a string. Behavior is the same idea.