Reputation: 5158
Uri targetUri = new Uri(targetURL);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string data = reader.ReadToEnd();
response.Close();
Why does the above code work fine but the following does not? Notice I close response early in the following code.
Uri targetUri = new Uri(targetURL);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
response.Close();
string data = reader.ReadToEnd();
Upvotes: 1
Views: 674
Reputation: 1499790
Closing the response closes the response stream as well... so the StreamReader
no longer has anything to read from.
From the documentation for WebResponse.Close
:
The Close method cleans up the resources used by a WebResponse and closes the underlying stream by calling the Stream.Close method.
Upvotes: 6
Reputation: 498904
Your reader was initialized with the stream from the response, so it is using it.
If you close the response stream, the reader no longer has a working underlying stream to read from.
Upvotes: 0