GetResponseStream读取字节

本文关键字:字节 读取 GetResponseStream | 更新日期: 2023-09-27 18:17:47

我正试图从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();

GetResponseStream读取字节

不要把它分成等量的步骤——相反,只要在循环中继续阅读,直到完成:

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的返回值——你不能假设会读取你请求的所有内容。