0

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?

2
  • It should refuse to compile (unassigned buffer) Commented Feb 28, 2012 at 23:14
  • 1
    @HenkHolterman: And trying to convert int to string too :) Commented Feb 28, 2012 at 23:20

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.