Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save WebResponse as txt

Tags:

c#

asp.net

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?

like image 546
Alberto León Avatar asked Sep 10 '12 08:09

Alberto León


Video Answer


2 Answers

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());
        }
    }
}
like image 166
sloth Avatar answered Oct 09 '22 23:10

sloth


WebClient class have ResponseHeaders collection :

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

like image 38
Antonio Bakula Avatar answered Oct 09 '22 22:10

Antonio Bakula