WebRequest GetResponseStream读取字节

时间:2011-12-13 14:11:44

标签: c# stream httpwebrequest webrequest

我正在尝试从ResponeStream读取字节,但我怎么说等待数据?

如果我在GetResponseStream之后设置一个断点并等待几秒钟,那么一切正常。 使用StreamReader.ReadToEnd()也可以正常工作,但我想自己读取字节。

byte[] response = null;

int left = 0;
int steps = 0;
int pos = 0;

int bytelength = 1024;

OnReceiveStart();

using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse()) {
    using (Stream sr = webResponse.GetResponseStream()) {

        response = new byte[(int)webResponse.ContentLength];

        left = (int)webResponse.ContentLength % bytelength;
        steps = (int)webResponse.ContentLength / bytelength;
        pos = 0;

        for (int i = 0; i < steps; i++) {
            sr.Read(response, pos, bytelength);
            pos += bytelength;
            OnReceiveProgress((int)webResponse.ContentLength, pos);
        }

        if (left != 0) {
            sr.Read(response, pos, left);
        }

        sr.Close();
    }
    webResponse.Close();
}

OnReceiveProgress(1, 1);

OnReceiveFinished();

1 个答案:

答案 0 :(得分:6)

请不要将其分解为相同数量的步骤 - 相反,只需继续阅读,直到完成为止:

while (pos < response.Length)
{
    int bytesRead = sr.Read(response, pos, response.Length - pos);
    if (bytesRead == 0)
    {
        // End of data and we didn't finish reading. Oops.
        throw new IOException("Premature end of data");
    }
    pos += bytesRead;
    OnReceiveProgress(response.Length, pos);
}

请注意,您必须使用Stream.Read的返回值 - 您不能假设它会读取您要求的所有内容。