jstedfast/MailKit · error · ArgumentOutOfRangeException

count

Error message

count

What it means

ArgumentOutOfRangeException raised inside TryQueueGetStreamCommand in ImapFolderFetch: the 'count' parameter (number of bytes to fetch from the stream at 'offset') was negative or out of range relative to the buffer, so the stream-fetch command could not be queued. This is a generic argument-range validation, not a server error.

Solutions

  1. Clamp count with Math.Max(0, count) before calling.
  2. Validate configured chunk sizes at startup.
  3. Note count == 0 is allowed and returns an empty stream; only negatives fail.

Example fix

// before
var count = remaining - fetched;
var stream = folder.GetStream(uid, offset, count);
// after
var count = Math.Max(0, remaining - fetched);
var stream = folder.GetStream(uid, offset, count);
Defensive patterns

Strategy: validation

Validate before calling

count = Math.Max(0, count);
var stream = folder.GetStream(uid, offset, count);

Try / catch

try { stream = folder.GetStream(uid, offset, count); }
catch (ArgumentOutOfRangeException ex) when (ex.ParamName == "count") { /* fix chunk-size math */ }

Prevention

When it happens

Trigger: Calling GetStream/GetStreamAsync (UID overload) with a negative count (ImapFolderFetch.cs:4190), typically from underflowed chunk math or mis-parsed sizes.

Common situations: Parsing byte counts from config strings into signed ints that go negative; subtracting larger progress counters; integer overflow wrapping negative.

Related errors


AI-assisted analysis of jstedfast/MailKit@9d3859a785 (2026-09-15). Data as JSON: /api/errors/36c43167425a47c8. Report an issue: GitHub.

Appendix: source

Thrown at MailKit/Net/Imap/ImapFolderFetch.cs:4190

			if (index < 0 || index >= Count)
				throw new ArgumentOutOfRangeException (nameof (index));

			if (part == null)
				throw new ArgumentNullException (nameof (part));

			return GetBodyPartAsync (index, part.PartSpecifier, cancellationToken, progress);
		}

		bool TryQueueGetStreamCommand (UniqueId uid, int offset, int count, CancellationToken cancellationToken, ITransferProgress? progress, [NotNullWhen (true)] out ImapCommand? ic, [NotNullWhen (true)] out FetchStreamContext? ctx)
		{
			if (!uid.IsValid)
				throw new ArgumentException ("The uid is invalid.", nameof (uid));

			if (offset < 0)
				throw new ArgumentOutOfRangeException (nameof (offset));

			if (count < 0)
				throw new ArgumentOutOfRangeException (nameof (count));

			CheckState (true, false);

			if (count == 0) {
				ctx = null;
				ic = null;
				return false;
			}

			ic = new ImapCommand (Engine, cancellationToken, this, "UID FETCH %u (BODY.PEEK[]<%d.%d>)\r\n", uid.Id, offset, count);
			ic.RegisterUntaggedHandler ("FETCH", FetchStreamHandler);
			ic.UserData = ctx = new FetchStreamContext (progress);

			Engine.QueueCommand (ic);

			return true;
		}

View on GitHub (pinned to 9d3859a785)