如何在C#中读取两次Http响应流?

时间:2008-09-29 08:29:15

标签: c# stream

我试图通过以下方式两次读取Http响应流:

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
stream = response.GetResponseStream();
RssReader reader = new RssReader(stream);
do
{
  element = reader.Read();
  if (element is RssChannel)
  {
    feed.Channels.Add((RssChannel)element);
  }
} while (element != null);

StreamReader sr = new StreamReader(stream);
feed._FeedRawData = sr.ReadToEnd();

然而,当StreamReader代码执行时,没有返回数据,因为流现在已经到了结尾。我尝试通过stream.Position = 0重置流但是这会引发异常(我认为因为流不能手动更改其位置)。

基本上,我想解析XML的流并且可以访问原始数据(以字符串格式)。

有什么想法吗?

3 个答案:

答案 0 :(得分:68)

首先将其复制到新的MemoryStream中。然后您可以根据需要多次重新读取MemoryStream:

Stream responseStream = CopyAndClose(resp.GetResponseStream());
// Do something with the stream
responseStream.Position = 0;
// Do something with the stream again


private static Stream CopyAndClose(Stream inputStream)
{
    const int readSize = 256;
    byte[] buffer = new byte[readSize];
    MemoryStream ms = new MemoryStream();

    int count = inputStream.Read(buffer, 0, readSize);
    while (count > 0)
    {
        ms.Write(buffer, 0, count);
        count = inputStream.Read(buffer, 0, readSize);
    }
    ms.Position = 0;
    inputStream.Close();
    return ms;
}

答案 1 :(得分:0)

按照MemoryStream的建议将流复制到Iain是正确的方法。但是由于 .NET Framework 4(2010年发布)具有Stream.CopyTo。来自文档的示例:

// Create the streams.
MemoryStream destination = new MemoryStream();

using (FileStream source = File.Open(@"c:\temp\data.dat",
    FileMode.Open))
{

    Console.WriteLine("Source length: {0}", source.Length.ToString());

    // Copy source to destination.
    source.CopyTo(destination);
}

Console.WriteLine("Destination length: {0}", destination.Length.ToString());

之后,您可以根据需要多次阅读destination

// re-set to beginning and convert stream to string
destination.Position = 0;
StreamReader streamReader = new StreamReader(destination);
string text = streamReader.ReadToEnd();
// re-set to beginning and read again
destination.Position = 0;
RssReader cssReader = new RssReader(destination);

(我见过Endy's comment,但由于它是当前的适当答案,因此应该有自己的答案条目。)

答案 2 :(得分:-1)

您是否尝试过重置流位置? 如果这不起作用,您可以将流复制到MemoryStream,然后您可以根据需要重置位置(即0)。