HttpWebResponse オブジェクトから応答ストリームを読み取ろうとしています。ストリームの長さ (_response.ContentLength) はわかっていますが、次の例外が引き続き発生します。
指定された引数は有効な値の範囲外です。パラメータ名:サイズ
デバッグ中に、エラーの時点で値が次のようになっていることに気付きました。
length = 15032 //_response.ContentLength で定義されたストリームの長さ
bytesToRead = 7680 //まだ読み取る必要があるストリーム内のバイト数
bytesRead = 7680 //読み取られたバイト数 (オフセット)
body.length = 15032 //ストリームがコピーされる byte[] のサイズ
奇妙な点は、ストリームのサイズ (長さ変数に含まれる) に関係なく、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;