Search code examples
c#.netstreamreaderwebrequesthttpwebresponse

How to read HttpWebResponse twice


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

My code doesn't work and respStream.Position = 0; does not help.

Any clues please?

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

Solution

  • 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
    }