0

我正在尝试从 HttpWebResponse 对象读取响应流。我知道流的长度(_response.ContentLength)但是我不断收到以下异常:

指定的参数超出了有效值的范围。参数名称:尺寸

在调试时,我注意到在错误发生时,值是这样的:

length = 15032 //流的长度由_response.ContentLength定义

bytesToRead = 7680 //流中还需要读取的字节数

bytesRead = 7680 //已读取的字节数(偏移量)

body.length = 15032 //流被复制到的字节[]的大小

奇怪的是 bytesToRead 和 bytesRead 变量总是 7680,不管流的大小(包含在长度变量中)。有任何想法吗?

代码:

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;
4

1 回答 1

2

你想要这条线:

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

变成这样:

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

您说要读取的最大字节数是流的长度,但事实并非如此,因为它实际上只是应用偏移后流中的剩余信息。

你也不应该需要这部分:

if (n == 0)
   break;

while 应该正确结束读取,并且在完成整个过程之前您可能不会读取任何字节(如果流的填充速度比您从中取出数据的速度慢)

于 2010-05-19T15:35:33.767 回答