IndexOutOfRangeException when a stream is a multiple of the buffer size

Posted by dnord on Stack Overflow See other posts from Stack Overflow or by dnord
Published on 2010-04-13T17:36:38Z Indexed on 2010/04/14 14:23 UTC
Read the original article Hit count: 231

I don't have a lot of experience with streams and buffers, but I'm having to do it for a project, and I'm stuck on an exception being thrown when the stream I'm reading is a multiple of the buffer size I've chosen. Let me show you:

My code starts by reading bufferSize (100, let's say) bytes from the stream:

numberOfBytesRead = DataReader.GetBytes(0, index, output, 0, bufferSize);

Then, I loop through a while loop:

while (numberOfBytesRead == bufferSize)
{
     BufferWriter.Write(output);
     BufferWriter.Flush();
     index += bufferSize;
     numberOfBytesRead = DataReader.GetBytes(0, index, output, 0, bufferSize);
}

... and, once we get to a non-bufferSize read, we know we've hit the end of the stream and can move on.

But if the bufferSize is 100, and the stream is 200, we'll read positions 0-99, 100-199, and then the attempt to read 200-299 errors out. I'd like it if it returned 0, but it throws an error. What I'm doing to handle that is, well, a try-catch:

catch (System.IndexOutOfRangeException)
    numberOfBytesRead = 0;

...which ends the loop, and successfully finishes the thing, but we all know I don't want to control code flow with error handling.

Is there a better (more standard?) way to handle stream reading when the stream length is unknown? This seems like a small wrinkle in a fairly reasonable strategy for reading streams, but I just don't know if I've got it wrong or what.

The specifics of this (which I've cleaned up a little bit for posting) are a MySqlDataReader hitting a LARGEBLOB column. It's working whenever the buffer is larger than the number of returned bytes, or when the number of returned bytes is not a multiple of bufferSize. Because we don't, in that case, throw an IndexOutOfRangeException.

© Stack Overflow or respective owner

Related posts about c#

Related posts about buffer