Dimi Dimi - 3 months ago 19
C# Question

How to read HttpWebResponse twice

How to read HttpWebResponse twise? Is it possible at all?

My code doesnt work and

respStream.Position = 0;
does not help.

Any clue, pls?

var data = (HttpWebRequest)WebRequest.Create(url);
var response = (HttpWebResponse)data.GetResponse();

var respStream = response.GetResponseStream();

string responseText;
using (var reader = new StreamReader(respStream, encoding))
{
responseText = reader.ReadToEnd().Trim();
}
// Do something and read it again
using (var reader = new StreamReader(respStream, encoding))
{
responseText = reader.ReadToEnd().Trim();
}

Answer

The type that is returned from response.GetResponseStream() is System.Net.ConnectStream. If you check the property CanSeek of this stream you will see that it cannot be seeked, so this means you cannot reset it and read it again:

var typeOfStream = respStream.GetType();    // System.Net.ConnectStream
var canSeek = respStream.CanSeek;           // false

However, when you read the data to a string you already have the data, so you can use it twice:

string responseText1, responseText2;
using (var reader = new StreamReader(respStream, encoding))
{
     responseText1 = reader.ReadToEnd().Trim();
     responseText2 = responseText1;    // you get a copy of response
}
Comments