How to convert WebResponse.GetResponseStream to string?

I see many examples, but they all read them in byte arrays or 256 characters at a time, slowly. Why?

Is it not recommended to simply convert the resulting Stream value to a string, where can I parse it?

+69
Sep 25 2018-11-11T00:
source share
5 answers

You must create a StreamReader around the stream, and then call ReadToEnd .

Instead, you should call WebClient.DownloadString .

+55
Sep 25 2018-11-11T00:
source share

You can use StreamReader.ReadToEnd() ,

 using (Stream stream = response.GetResponseStream()) { StreamReader reader = new StreamReader(stream, Encoding.UTF8); String responseString = reader.ReadToEnd(); } 
+116
Sep 25 2018-11-11T00:
source share

As @Heinzi pointed out, the response character set should be used.

  var encoding = response.CharacterSet == "" ? Encoding.UTF8 : Encoding.GetEncoding(response.CharacterSet); using (var stream = response.GetResponseStream()) { var reader = new StreamReader(stream, encoding); var responseString = reader.ReadToEnd(); } 
+4
Oct 09 '15 at 15:22
source share
Richard Schneider is right. use the code below to retrieve data from a site that is not utf8 encoded, will receive the wrong string.
 using (Stream stream = response.GetResponseStream()) { StreamReader reader = new StreamReader(stream, Encoding.UTF8); String responseString = reader.ReadToEnd(); } 

"I can’t vote. So wrote it.

+3
Aug 27 '16 at 4:53 on
source share

You can create a StreamReader around the stream, and then call StreamReader.ReadToEnd() .

 StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream()); var responseData = responseReader.ReadToEnd(); 
+2
Aug 11 '15 at 11:40
source share



All Articles