如何读两遍
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”提供的解决方案会更干净、更快。