Streamreader does not work when I close HttpWebResponse early
Uri targetUri = new Uri(targetURL);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUr开发者_StackOverflow中文版i);
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();
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.
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.
精彩评论