简体   繁体   English

在 C# 中将 HTTP 流保存到文件

[英]Save a HTTP stream to file in c#

Im getting a XML-response as a HTTPresponse, that works well.我得到一个 XML 响应作为 HTTP 响应,效果很好。 Now im trying to save it to disc for future usage as well.现在我试图将它保存到光盘以备将来使用。 Im trying to use the second method described in How do I save a stream to a file in C#?我正在尝试使用如何在 C# 中将流保存到文件中描述的第二种方法 (did not get the first method to work either). (也没有让第一种方法起作用)。 The file is created but empty该文件已创建但为空

Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);

XmlDocument events = new XmlDocument();
events.Load(reader);

var fileStream = File.Create("C:\\XMLfiles\\test.xml");
CopyStream(dataStream, fileStream);
fileStream.Close();

public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[8 * 1024];
    int len;
    while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, len);
    }
}

Please use following code snippet.请使用以下代码片段。 Don't forget about "using" approach!不要忘记“使用”方法!

HttpWebRequest tt = HttpWebRequest.CreateHttp("http://www.stackoverflow.com");

            using (var yy = tt.GetResponse())
            using (var stream = yy.GetResponseStream())
            using (var file = File.Open(@"c:\response.html", FileMode.Create))
            {
                stream.CopyTo(file);
                stream.Flush();
            }

This is a tricky situation.这是一个棘手的情况。 The problem is you read the HttpResponseStream already.问题是您已经阅读了HttpResponseStream As a result, you're at the end of the stream.结果,您处于流的末尾。 Under normal circumstances you'd just set dataStream.Position = 0 .在正常情况下,您只需设置dataStream.Position = 0 However, you can't do that here because we're not talking about a file on your PC, it's a network stream so you can't "go backwards" (it was already sent to you).但是,你不能在这里这样做,因为我们不是在谈论你 PC 上的文件,它是一个网络流,所以你不能“倒退”(它已经发送给你)。 As a result, what I'd recommend you do is instead of trying to write the original stream again, write your XmlDocument .因此,我建议您不要尝试再次编写原始流,而是编写您的XmlDocument

Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);

XmlDocument events = new XmlDocument();
events.Load(reader);
events.Save("C:\\XMLfiles\\test.xml");

In that case it will work since you're saving the data that's been copied to the XmlDocument rather than trying to reread a network stream.在这种情况下,它将起作用,因为您正在保存已复制到XmlDocument的数据,而不是尝试重新读取网络流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM