如何读取 HttpWebResponse 两次

How to read HttpWebResponse twice

如何读懂HttpWebResponse?有可能吗?

我的代码不起作用,respStream.Position = 0; 没有帮助。

有什么线索吗?

var data = (HttpWebRequest)WebRequest.Create(url);  
var response = (HttpWebResponse)data.GetResponse();

var respStream = response.GetResponseStream();

string responseText;         
using (var reader = new StreamReader(respStream, encoding))
{
     responseText = reader.ReadToEnd().Trim();
}
// Do something and read it again
using (var reader = new StreamReader(respStream, encoding))
{
     responseText = reader.ReadToEnd().Trim();
}

response.GetResponseStream() 返回的类型是 System.Net.ConnectStream。如果你检查这个流的 属性 CanSeek 你会看到它不能被搜索,所以这意味着你不能重置它并再次阅读它:

var typeOfStream = respStream.GetType();    // System.Net.ConnectStream
var canSeek = respStream.CanSeek;           // false

然而,当你将数据读入一个字符串时,你已经有了数据,所以你可以使用它两次:

string responseText1, responseText2;
using (var reader = new StreamReader(respStream, encoding))
{
     responseText1 = reader.ReadToEnd().Trim();
     responseText2 = responseText1;    // you get a copy of response
}

我遇到了类似的问题,但我的流不包含字符串内容,而是包含二进制数据。由于我们只能读取一次 ConnectStream,我的解决方案是将其复制到 MemoryStream:

WebRequest request = WebRequest.Create("http://www.foo.bar/binary.file");
using (WebResponse response = request.GetResponse())
{
    var responseStream = response.GetResponseStream();

    using (var memoryStream = new MemoryStream())
    {
        responseStream.CopyTo(memoryStream);

        // This one is important so we can read the stream from the beginning.
        memoryStream.Seek(0, SeekOrigin.Begin); 

        // Perform my first thing.
        var isValid = Utility.ValidateContent(memoryStream);

        if (isValid)
        {
            // Reset the position to the beginning of the stream again
            memoryStream.Seek(0, SeekOrigin.Begin); 
            using (var fileStream = File.Create("c:\temp\myfile.ext"))
            {
                memoryStream.CopyTo(fileStream);
            }
        }
    }
}

明确地说,如果只需要两倍的字符串数据,"dotnetom" 提供的解决方案会更干净、更快。