dotnet/maui · error · FormatException

Bad value for origin

Error message

Bad value for origin

What it means

StringStream.Seek switches on the SeekOrigin enum (Begin, Current, End) and throws FormatException for any other value. Since SeekOrigin is a well-known BCL enum, the default branch is only reachable if the enum is cast from an out-of-range integer. The error indicates a corrupted or illegally-cast SeekOrigin value.

Source

Thrown at src/Compatibility/Core/src/WPF/Microsoft.Windows.Shell/Standard/StreamHelper.cs:702

            }
            return cbRead;
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            switch (origin)
            {
                case SeekOrigin.Begin:
                    Position = offset;
                    break;
                case SeekOrigin.Current:
                    Position += offset;
                    break;
                case SeekOrigin.End:
                    Position = Length + offset;
                    break;
                default:
                    throw new FormatException("Bad value for origin");
            }
            return Position;
        }

        public override void SetLength(long value)
        {
            throw new NotSupportedException();
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            throw new NotSupportedException();
        }
    }
#endif
}

View on GitHub (pinned to f377ff1c5e)

Solutions

  1. Validate that origin is one of SeekOrigin.Begin, SeekOrigin.Current, or SeekOrigin.End before calling Seek.
  2. If the origin arrives as an int from interop, map it through a known mapping table and reject unknown values upstream.
  3. Use Enum.IsDefined(typeof(SeekOrigin), value) to guard against out-of-range casts.

Example fix

// before
stream.Seek(offset, (SeekOrigin)originInt);

// after
if (!Enum.IsDefined(typeof(SeekOrigin), originInt))
{
    throw new ArgumentOutOfRangeException(nameof(originInt));
}
stream.Seek(offset, (SeekOrigin)originInt);
Defensive patterns

Strategy: validation

Validate before calling

// Validate SeekOrigin before calling Seek
if (!Enum.IsDefined(typeof(SeekOrigin), origin))
{
    throw new ArgumentOutOfRangeException(nameof(origin), "Invalid SeekOrigin value.");
}
stream.Seek(offset, origin);

Prevention

When it happens

Trigger: Calling Seek on a StringStream with a SeekOrigin value produced by casting an integer that is not 0, 1, or 2 — e.g. (SeekOrigin)42. This is typically a programming bug rather than a data-driven condition.

Common situations: Interop code that marshals an integer origin from native code without validation; deserialization of a SeekOrigin from untrusted or corrupt data; accidental arithmetic on the enum before passing it.

Related errors


AI-assisted analysis of dotnet/maui@f377ff1c5e (2026-08-13). Data as JSON: /api/errors/163056fe49639906. Report an issue: GitHub.