How to convert WebResponse.GetResponseStream return into a string?

前端 未结 5 1196
春和景丽
春和景丽 2020-12-05 12:17

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

5条回答
  •  独厮守ぢ
    2020-12-05 13:00

    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();
    }
    

提交回复
热议问题