Base64 in .NET
- Encode:
Convert.ToBase64String(bytes). For text, choose the bytes first:Encoding.UTF8.GetBytes(text).Base64FormattingOptions.InsertLineBreaksadds a CRLF every 76 characters, as MIME email does. - Decode:
Convert.FromBase64Stringignores spaces, tabs and line breaks anywhere, but the rest must be a multiple of four characters, with at most two=at the end. Otherwise it throws a FormatException: "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." From .NET 11 it also throws when the unused bits of the last character are not zero: "QR==" throws and "QQ==" decodes to the byte 0x41. .NET 10 and earlier ignore those bits and decode "QR==" to 0x41 too. Base64Url andBase64.DecodeFromUtf8already rejected such input. - Base64Url (URLs, file names, JWTs) uses
-and_instead of+and/and drops the padding.Convert.FromBase64Stringrejects it; on .NET 9 and later useSystem.Buffers.Text.Base64Url, which accepts it with or without padding. JWT parts are Base64Url; the JWT decoder reads them for you.
FAQ
Why does Convert.FromBase64String throw a FormatException?
The text has characters outside A-Z, a-z, 0-9, + and / (often - and _ from Base64Url), a length that is not a multiple of 4 because the = padding was removed, or = in the middle. On .NET 11 it also throws when the unused bits of the last character are not zero, as in "QR=="; .NET 10 and earlier decode that to the same byte as "QQ==".
How do I decode Base64Url in C#?
On .NET 9 and later: Base64Url.DecodeFromChars(text). Before that, replace - with + and _ with /, add = until the length is a multiple of 4, then call Convert.FromBase64String.
Is Base64 encryption?
No. Anyone can decode it. It only turns bytes into text that survives JSON, URLs and email.
Why does decoded Base64 look like garbage?
The bytes are not text in the encoding you chose: they may be an image, a compressed file, or text in UTF-16. Try another encoding, or treat the bytes as a file.





