Stefan Magnusson
Stefan Magnusson

Reputation: 23

Save a HTTP stream to file in c#

Im getting a XML-response as a HTTPresponse, that works well. 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#? (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);
    }
}

Upvotes: 2

Views: 6083

Answers (2)

Anton Norka
Anton Norka

Reputation: 2322

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();
}

Upvotes: 3

dmeglio
dmeglio

Reputation: 2830

This is a tricky situation. The problem is you read the HttpResponseStream already. As a result, you're at the end of the stream. Under normal circumstances you'd just set 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). As a result, what I'd recommend you do is instead of trying to write the original stream again, write your 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.

Upvotes: 0

Related Questions