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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/147941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 15:35:40  来源:igfitidea点击:

How can I read an Http response stream twice in C#?

提问by greg7gkb

I am trying to read an Http response stream twice via the following:

我试图通过以下方式读取 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();

However when the StreamReader code executes there is no data returned because the stream has now reached the end. I tried to reset the stream via stream.Position = 0 but this throws an exception (I think because the stream can't have its position changed manually).

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

Basically, I would like to parse the stream for XML and have access to the raw data (in string format).

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

Any ideas?

有任何想法吗?

采纳答案by Iain

Copy it into a new MemoryStream first. Then you can re-read the MemoryStream as many times as you like:

首先将其复制到新的 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;
}

回答by Joachim Kerschbaumer

have you tried resetting the stream position? if this does not work you can copy the stream to a MemoryStream and there you can reset the position (i.e. to 0) as often as you want.

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

回答by Hyman Miller

Copying the stream to a MemoryStreamas suggested by Iainis the right approach. But since .NET Framework 4 (released 2010) we have Stream.CopyTo. Example from the docs:

按照Iain 的建议将流复制到MemoryStream是正确的方法。但是从 .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());

Afterwards you can read destinationas many times as you like:

之后,您可以随意阅读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);

(I have seen Endy's commentbut since it is an appropriate, current answer, it should have its own answer entry.)

(我已经看到Endy 的评论,但由于它是一个合适的当前答案,它应该有自己的答案条目。)