6

I'm looking for a method equivalent to Request.SaveAs in WebResponse. But I can't find it.

I want to store in txt file the headers and the body of a webresponse.

Do you know any technique to achieve it?

Alberto León
  • 2,879
  • 2
  • 25
  • 24

2 Answers2

9

There's no builtin way, but you can simply use the GetResponseStream method to get the responce stream and save it to a file.


Example:

WebRequest myRequest = WebRequest.Create("http://www.example.com");
using (WebResponse myResponse = myRequest.GetResponse())
using (StreamReader reader = new StreamReader(myResponse.GetResponseStream()))
{
    // use whatever method you want to save the data to the file...
    File.AppendAllText(filePath, myResponse.Headers.ToString());
    File.AppendAllText(filePath, reader.ReadToEnd());
}

Nonetheless, you can wrap it into an extension method

WebRequest myRequest = WebRequest.Create("http://www.example.com");
using (WebResponse myResponse = myRequest.GetResponse())
{
    myResponse.SaveAs(...)
}

...

public static class WebResponseExtensions
{
    public static void SaveAs(this WebResponse response, string filePath)
    {
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            File.AppendAllText(filePath, myResponse.Headers.ToString());
            File.AppendAllText(filePath, reader.ReadToEnd());
        }
    }
}
sloth
  • 99,095
  • 21
  • 171
  • 219
  • Is a good way to do it. Why annidate the usings? Should be best run one using and later the second? – Alberto León Sep 10 '12 at 08:43
  • I think using StringBuilder you gain clearity and only writes one time to disk: `code` StringBuilder sb = new StringBuilder(); sb.Append(response.Headers.ToString()); sb.AppendLine(); sb.Append(responseTxt); File.AppendAllText(filePath, sb.ToString()); `code` – Alberto León Sep 10 '12 at 09:34
  • Note, this will buffer all the request in memory. You wouldn't be able to download files >512Mb on 32bit OS. And in this case you would "download it to swap first" – bohdan_trotsenko Jun 04 '16 at 21:20
  • There's a bigger problem with encoding too. – bohdan_trotsenko Jun 04 '16 at 21:20
1

WebClient class have ResponseHeaders collection :

http://msdn.microsoft.com/en-us/library/system.net.webclient.responseheaders.aspx

Antonio Bakula
  • 20,445
  • 6
  • 75
  • 102