views:

54

answers:

1

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;
A: 

You want this line:

int n = stream.Read(body, bytesRead, length);

to be this:

int n = stream.Read(body, bytesRead, bytesToRead);

You are saying the maximum number of bytes to read is the stream's length, but it isn't since it is actually only the remaining information in the stream after the offset has been applied.

You also shouldn't need this part:

if (n == 0)
   break;

The while should end the reading correctly, and it is possible that you won't read any bytes before you have finished the whole thing (if the stream is filling slower than you are taking the data out of it)

Martin Harris
You, sir, are a genius. How would I go about remedying the second problem (stream filling slower than I am reading it)? Wouldn't setting bytesToRead = length ensure that all of the bytes of the stream were being read?