本文介绍了保存WebResponse类为TXT文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在寻找一种方法相当于Request.SaveAs在WebResponse的。但我不能找到它。
I'm looking for a method equivalent to Request.SaveAs in WebResponse. But I can't find it.
我想txt文件来存储头部和WebResponse的身上。
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.
示例:
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());
}
}
}
这篇关于保存WebResponse类为TXT文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!