Save WebResponse as txt

I am looking for a method equivalent to Request.SaveAs in WebResponse. But I canโ€™t find him.

I want to save the headers and body of the message in a txt file.

Do you know any technique to achieve it?

+4
source share
2 answers

There is no built-in way, but you can simply use the GetResponseStream method to get the response 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()); } 

However, you can wrap it in 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()); } } } 
+7
source
+1
source

Source: https://habr.com/ru/post/1433313/


All Articles