Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Can I Only Call GetResponseStream() Once

Tags:

c#

I've just noticed some behavior in C# that's thrown me off a little. I'm using C# 5 and .NET 4.5. When I call GetResponseStream() on a HTTPResponse object I am able to get the response stream, but if I call it again on the same object the response is blank.

// Works! Body of the response is in the source variable.
HttpResponse response = (HttpWebResponse)request.GetResponse();
String source = new StreamReader(response.GetResponseStream()).ReadToEnd();

// Does Not Work. Source is empty;
String source2 = new StreamReader(response.GetResponseStream()).ReadToEnd();

The above is just an example to demonstrate the problem.

Edit

This is what I'm trying to do. Basically if an event is attached to the HTTP object it will pass a response back to the callback method.

HttpWebResponse public Get(String url)
{
    // HttpWebRequest ...

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    // postRequest is an event handler. The response is passed to the
    // callback to do whatever it needs to do.
    if (this.postRequest != null)
    {
        RequestEventArgs requestArgs = new RequestEventArgs();
        requestArgs.source = response;
        postRequest.Invoke(this, requestArgs);
    }

    return response;
}

In the callback method I may want to check the body of the response. If I do, I lose the the data from the response when Get() returns the response.

like image 807
James Jeffery Avatar asked Nov 19 '25 13:11

James Jeffery


1 Answers

The response stream reads directly from the network connection.

Once you read it to the end (in the 2nd line), there is no more data to read.

like image 122
SLaks Avatar answered Nov 21 '25 05:11

SLaks