OrchardCMS/OrchardCore · error · FormatException

Invalid Base64 string.

Error message

Invalid Base64 string.

What it means

Base64.FromUTF8Base64String decodes a Base64-encoded UTF-8 string in-place and throws FormatException when Convert.TryFromBase64String fails, i.e. the input contains characters or padding that are not valid Base64.

Solutions

  1. Validate the input matches the Base64 pattern before calling (see validationCode).
  2. Determine whether the sender used Base64Url encoding (- and _ instead of + and /) and normalize accordingly.
  3. Fix the producer of the string so a properly encoded Base64 value is stored/transmitted.
  4. Catch FormatException and surface a user-friendly 'invalid encoded value' message.

Example fix

// before
var text = Base64.FromUTF8Base64String(input); // throws on url-safe base64
// after
var normalized = input.Replace('-', '+').Replace('_', '/');
var text = Base64.FromUTF8Base64String(normalized);
Defensive patterns

Strategy: validation

Validate before calling

private static readonly System.Text.RegularExpressions.Regex Base64Rx =
    new("^[A-Za-z0-9+/]*={0,2}$", System.Text.RegularExpressions.RegexOptions.Compiled);

bool IsValidBase64(string s) =>
    !string.IsNullOrEmpty(s) && s.Length % 4 == 0 && Base64Rx.IsMatch(s);

Type guard

static bool IsBase64String([System.Diagnostics.CodeAnalysis.NotNullWhen(true)] string? s) =>
    !string.IsNullOrEmpty(s) && s.Length % 4 == 0 &&
    Convert.TryFromBase64String(s, new byte[s.Length], out _);

Try / catch

try
{
    var text = Base64.FromUTF8Base64String(input);
}
catch (FormatException)
{
    throw new ArgumentException("The provided value is not a valid Base64 string.", nameof(input));
}

Prevention

When it happens

Trigger: Passing a string with characters outside the Base64 alphabet (A–Z, a–z, 0–9, +, /), wrong length (not a multiple of 4), or truncated/misplaced padding to FromUTF8Base64String.

Common situations: Storing an already-decoded string instead of the encoded one; URL-safe tokens edited/truncated by copy-paste; data corrupted by a form/JSON round-trip.

Understand the failure class

Background: "Invalid ... format", "must be in format X", "does not look like a ..." — invalid argument format errors across CLI tools and libraries — this error's family across 17 libraries.

Related errors


AI-assisted analysis of OrchardCMS/OrchardCore@4306c0717f (2026-09-13). Data as JSON: /api/errors/5d85d45549a922fd. Report an issue: GitHub.

Appendix: source

Thrown at src/OrchardCore/OrchardCore.Abstractions/Base64.cs:25

    /// <summary>
    /// Converts a base64 encoded UTF8 string to the original value.
    /// </summary>
    /// <param name="base64">The base64 encoded string.</param>
    /// <returns>The decoded string.</returns>
    /// <remarks>This method is equivalent to <c>Encoding.UTF8.GetString(Convert.FromBase64String(base64))</c> but uses a buffer pool to decode the string.</remarks>
    public static string FromUTF8Base64String(string base64)
    {
        ArgumentNullException.ThrowIfNull(base64);

        // Due to padding the deserialized buffer could be smaller than this value.
        var maxBufferLength = GetDeserializedBase64Length(base64.Length);

        using var memoryStream = MemoryStreamFactory.GetStream(maxBufferLength);
        var span = memoryStream.GetSpan(maxBufferLength);

        if (!Convert.TryFromBase64String(base64, span, out var bytesWritten))
        {
            throw new FormatException("Invalid Base64 string.");
        }

        return Encoding.UTF8.GetString(span.Slice(0, bytesWritten));
    }

    [Obsolete("This will be deprecated in v4. Please use DecodeToStream instead.")]
    public static Stream DecodedToStream(string base64)
        => DecodeToStream(base64);

    /// <summary>
    /// Converts a base64 encoded string to a stream.
    /// </summary>
    /// <param name="base64">The base64 encoded string.</param>
    /// <remarks>The resulting <see cref="Stream"/> is positioned at index 0 and should be disposed once used.</remarks>
    /// <returns>The decoded stream.</returns>
    /// <exception cref="FormatException"></exception>
    public static Stream DecodeToStream(string base64)
    {

View on GitHub (pinned to 4306c0717f)