Joan Venge
Joan Venge

Reputation: 330922

How to convert WebResponse.GetResponseStream return into a string?

I see many examples but all of them read them into byte arrays or 256 chars at a time, slowly. Why?

Is it not advisable to just convert the resulting Stream value into a string where I can parse it?

Upvotes: 88

Views: 149043

Answers (5)

Richard Schneider
Richard Schneider

Reputation: 35477

As @Heinzi mentioned the character set of the response 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();
}

Upvotes: 16

Howard Lou
Howard Lou

Reputation: 79

Richard Schneider is right. use code below to fetch data from site which is not utf8 charset will get wrong string.

using (Stream stream = response.GetResponseStream())
{
   StreamReader reader = new StreamReader(stream, Encoding.UTF8);
   String responseString = reader.ReadToEnd();
}

" i can't vote.so wrote this.

Upvotes: 7

Mari
Mari

Reputation: 247

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

StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
var responseData = responseReader.ReadToEnd();

Upvotes: 3

KV Prajapati
KV Prajapati

Reputation: 94645

You can use StreamReader.ReadToEnd(),

using (Stream stream = response.GetResponseStream())
{
   StreamReader reader = new StreamReader(stream, Encoding.UTF8);
   String responseString = reader.ReadToEnd();
}

Upvotes: 153

SLaks
SLaks

Reputation: 887365

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

You should consider calling WebClient.DownloadString instead.

Upvotes: 61

Related Questions