dotnet/wpf · error · ArgumentException

A read or write operation references a location outside the…

Error message

A read or write operation references a location outside the bounds of the buffer provided.

What it means

NetStream.Read validates that offset+count does not exceed the caller-supplied buffer length inside a checked block, throwing ArgumentException (SR.IOBufferOverflow) when the read would run past the end of the buffer. This library throws it to prevent writing more bytes into 'buffer' than it can hold.

Solutions

  1. Pass count <= buffer.Length - offset
  2. Compute the read size as Math.Min(desired, buffer.Length - offset)
  3. Check the buffer slice before calling Read; use ArraySegment or Span-based overloads where available

Example fix

// before
stream.Read(buffer, buffer.Length - 2, 64);
// after
int toRead = Math.Min(64, buffer.Length - (buffer.Length - 2));
stream.Read(buffer, buffer.Length - 2, toRead);
Defensive patterns

Strategy: validation

Validate before calling

int toRead = Math.Min(desired, buffer.Length - offset);
if (toRead < 0) throw new ArgumentException("offset beyond buffer end");
int read = stream.Read(buffer, offset, toRead);

Type guard

static bool IsValidReadRange(byte[] buffer, int offset, int count) => buffer != null && offset >= 0 && count >= 0 && offset + count <= buffer.Length;

Try / catch

try { bytesRead = stream.Read(buffer, offset, count); } catch (ArgumentException ex) when (ex.ParamName == "buffer") { log.Error("Read exceeds buffer bounds", ex); }

Prevention

When it happens

Trigger: Calling Read(byte[] buffer, int offset, int count) where offset + count > buffer.Length, e.g. passing an offset near the end of a small buffer with a large count.

Common situations: Computing count from stream Length instead of remaining buffer space; reusing a large count value across multiple reads into progressively smaller buffers; off-by-one when reserving room for a terminator byte.

Related errors


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

Appendix: source

Thrown at src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/IO/Packaging/NetStream.cs:141

        {
            CheckDisposed();
#if DEBUG
            if (System.IO.Packaging.PackWebRequestFactory._traceSwitch.Enabled)
                System.Diagnostics.Trace.TraceInformation("NetStream.Read() offset:{0} length:{1}", _position, count );
#endif

            PackagingUtilities.VerifyStreamReadArgs(this, buffer, offset, count);

            // quick exit
            if (count == 0)
                return count;

            int bytesRead = 0;

            checked
            {
                if (offset + count > buffer.Length)
                    throw new ArgumentException(SR.IOBufferOverflow, nameof(buffer));

                // make sure some data is in the stream - block until it is
                int bytesAvailable = GetData(new Block(_position, count));
                count = Math.Min(bytesAvailable, count);    // don't return more than they requested, and don't return more than is available

                // read into the buffer and return (if any data is available)
                if (count > 0)
                {
                    try
                    {
                        _tempFileMutex.WaitOne();

                        lock (PackagingUtilities.IsolatedStorageFileLock)
                        {
                            _tempFileStream.Seek(_position, SeekOrigin.Begin);      // align the temp stream with our logical position
                            bytesRead = _tempFileStream.Read(buffer, offset, count);     // read from the temp file
                        }
                    }

View on GitHub (pinned to 81131a70a4)