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();
为什么上面的代码可以正常工作而下面的却不行? 请注意,我在以下代码中提前关闭了响应。
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();
最佳答案
关闭响应也会关闭响应流...因此 StreamReader
不再有任何可读取的内容。
来自 WebResponse.Close
的文档:
The Close method cleans up the resources used by a WebResponse and closes the underlying stream by calling the Stream.Close method.
关于c# - 当我提前关闭 HttpWebResponse 时,Streamreader 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4327973/