ArgumentOutOfRangeException when reading bytes from stream

Posted by user345194 on Stack Overflow See other posts from Stack Overflow or by user345194
Published on 2010-05-19T15:28:27Z Indexed on 2010/05/19 15:30 UTC
Read the original article Hit count: 322

Filed under:
|
|
|

I'm trying to read the response stream from an HttpWebResponse object. I know the length of the stream (_response.ContentLength) however I keep getting the following exception:

Specified argument was out of the range of valid values. Parameter name: size

While debugging, I noticed that at the time of the error, the values were as such:

length = 15032 //the length of the stream as defined by _response.ContentLength

bytesToRead = 7680 //the number of bytes in the stream that still need to be read

bytesRead = 7680 //the number of bytes that have been read (offset)

body.length = 15032 //the size of the byte[] the stream is being copied to

The peculiar thing is that the bytesToRead and bytesRead variables are ALWAYS 7680, regardless of the size of the stream (contained in the length variable). Any ideas?

Code:

int length = (int)_response.ContentLength;

byte[] body = null;

if (length > 0) { int bytesToRead = length; int bytesRead = 0;

try
{
    body = new byte[length];

    using (Stream stream = _response.GetResponseStream())
    {
        while (bytesToRead > 0)
        {                                                        
            // Read may return anything from 0 to length.
            int n = stream.Read(body, bytesRead, length);

            // The end of the file is reached.
            if (n == 0)
                break;

            bytesRead += n;
            bytesToRead -= n;
        }
        stream.Close();
    }
}
catch (Exception exception)
{
    throw;
}   

} else { body = new byte[0]; }

_responseBody = body;

© Stack Overflow or respective owner

Related posts about httpwebresponse

Related posts about c#