Reading WebRequest Bytes GetResponseStream

I am trying to read bytes from a ResponeStream, but how can I say to wait for data?

If you set a breakpoint after GetResponseStream and wait a few seconds, everything will be fine. Using StreamReader.ReadToEnd () also works great, but I want to read the bytes myself.

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();
+5
source share
1 answer

Just don't break it down into an equal number of steps - instead, just keep reading in a loop until you're done:

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);
}

Note that you must use the return value Stream.Read- you cannot assume that it will read everything that you requested.

+6
source

All Articles