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?
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());
}
}
}
WebClient class have ResponseHeaders collection :
http://msdn.microsoft.com/en-us/library/system.net.webclient.responseheaders.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With