Read everything in a Stream into a string

  • Thread starter Thread starter Fernando Rodríguez
  • Start date Start date
F

Fernando Rodríguez

Hi,

How can I read everything inside a Stream into a String or StringBuilder? O:-)

TIA
 
Fernando,

If you know the encoding for the stream, just wrap the stream in a
StreamReader, and call the ReadToEnd. Be careful if you are reading from a
network stream, as this will cause it to hang if the stream is not
disconnected when done (as opposed to reading messages from the stream and
keeping it open).

Hope this helps.
 
Does the Stream object represent just a character stream? In this case, you
can wrap it in a StreamReader and use its ReadToEnd method to read the whole
thing at once. This method returns a string.
 
Fernando,

If you know the encoding for the stream, just wrap the stream in a
StreamReader, and call the ReadToEnd. Be careful if you are reading from a
network stream, as this will cause it to hang if the stream is not
disconnected when done (as opposed to reading messages from the stream and
keeping it open).

Actually it's the return value of HttpWebResponse.GetResponseStream().

I'm afraid that what I need is a better understanding of Streams. Could you
point out some tutorial that cover streams and specifically network streams?
O:-)

TIA
 
Does the Stream object represent just a character stream? In this case, you

It's an httpresponse for a web page, so yes, I guess it can only be text.
can wrap it in a StreamReader and use its ReadToEnd method to read the whole
thing at once. This method returns a string.

OK :-)
 
Fernando,

You should be alright if you are using GetResponseStream. It should
allow you to call ReadToEnd on the stream and get the result.

If you were using a NetworkStream though, it's different, as you can
send say, 32 over the wire (a space), but still have a connection, so the
stream is not complete yet. If you called ReadToEnd on that, then it would
wait for all of the bytes, and then for the stream to close, and therefore,
block.
 
Back
Top