简体   繁体   中英

Reading A stream through stream.read instead of using a StreamReader

I am trying to get a request and read it like:

byte[] buffer;
Stream read = http.GetResponseStream();
string readIt = read.Read(buffer, 0, read.Length)

But it throws an error with invalid argument.

Any idea how to get that response to a string while using Stream instead of a StreamReader?

That's because you haven't created the byte array that you try to use.

byte[] buffer = new byte[read.Length];

Note though that you should check the value of read.Length before you use it. The response length is not always known.

Also, the Read method returns an int , not a string .

Also, and this is very important, you have to use the return value from the Read method, as it tells you how many bytes were actually read. The Read method doesn't have to return all the bytes that you ask for, so you have to loop until it returns the value zero, which means that the stream has been read to the end:

int offset = 0, len;
do {
  len = read.Read(buffer, offset, read.Length - offset);
  offset += len;
} while (len > 0);

// now offset contains the number of bytes read into the buffer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM