我正在尝试从 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;