c# - 当我提前关闭 HttpWebResponse 时,Streamreader 不工作

标签 c# httpwebresponse streamreader

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/

相关文章:

c# - 常规使用 soap 错误的 WCF 客户端的处置

c# - 如何使用 .NET HttpWebRequest API 从响应中读取 HTTP header ?

c# - 400 错误请求 |从 ASP.NET Web API 接收自定义错误消息或模型

c# - HttpWebRequest 登录数据 然后重定向

c# - 使用正则表达式读入文件?

c# - 以非升序从大文件中读取多行

c# - 批量插入记录到 SQL Server 数据库

c# - 由于空引用,订阅的事件未触发

c# - 如何从其隐藏代码访问资源字典中的控件?

c# - 如何使用 .net 读取包含 2900 万行数据的巨大 CSV 文件