dotnet/wpf · error · NotSupportedException

Stream does not support SetLength.

Error message

Stream does not support SetLength.

What it means

DeobfuscatingStream is read-only, so SetLength unconditionally throws NotSupportedException (SR.SetLengthNotSupported) after a disposal check. Resizing the stream is not a supported operation. (The message shown, 'Stream does not support SetLength.', is the standard NotSupportedException wording for this case.)

Solutions

  1. Don't resize a DeobfuscatingStream; it reflects a fixed-size source file
  2. Perform the resize on the underlying FileStream if you own the file
  3. Check stream.CanSeek/CanWrite and skip SetLength for read-only streams

Example fix

// before
stream.SetLength(newLen);
// after
if (stream.CanWrite) stream.SetLength(newLen);
Defensive patterns

Strategy: type-guard

Validate before calling

if (!stream.CanWrite) skip SetLength / use underlying file;

Type guard

static bool SupportsResize(Stream s) => s.CanWrite && s.CanSeek;

Try / catch

try { stream.SetLength(newLen); } catch (NotSupportedException) { /* resize underlying FileStream instead */ }

Prevention

When it happens

Trigger: Calling SetLength(long) — directly or indirectly via StreamWriter construction, SetLength in a copy routine, or truncation attempts — on a DeobfuscatingStream.

Common situations: Code paths that resize streams generically (e.g. truncating before rewrite) applied to an obfuscated XPS stream.

Understand the failure class

Background: UnsupportedOperationException and "is not supported" errors: when a library deliberately refuses a call — this error's family across 30 libraries.

Related errors


AI-assisted analysis of dotnet/wpf@81131a70a4 (2026-09-14). Data as JSON: /api/errors/d2c6f2b164caa902. Report an issue: GitHub.

Appendix: source

Thrown at src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/DeobfuscatingStream.cs:95

        /// </summary>
        /// <param name="offset">offset</param>
        /// <param name="origin">origin</param>
        public override long Seek(long offset, SeekOrigin origin)
        {
            CheckDisposed();

            return _obfuscatedStream.Seek(offset, origin);
        }

        /// <summary>
        /// SetLength
        /// </summary>
        /// <remarks>This is a read-only stream; throw now supported exception</remarks>
        public override void SetLength(long newLength)
        {
            CheckDisposed();

            throw new NotSupportedException(SR.SetLengthNotSupported);
       }

        /// <summary>
        /// Flush
        /// </summary>
        public override void Flush()
        {
            CheckDisposed();

            _obfuscatedStream.Flush();
        }
        #endregion Stream Methods

        #region Stream Properties
        /// <summary>
        /// Current position of the stream
        /// </summary>
        public override long Position

View on GitHub (pinned to 81131a70a4)