在 .NET 中从 URL 读取字符串的最简单方法
给定字符串中的 URL:
http://www.example.com/test.xml
将文件内容从服务器(由 url 指向)下载到 C# 中的字符串中的最简单/最简洁的方法是什么?
我目前的做法是:
WebRequest request = WebRequest.Create("http://www.example.com/test.xml");
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
这是很多代码,本质上可能是一行:
string responseFromServer = ????.GetStringFromUrl("http://www.example.com/test.xml");
注意:我不担心异步调用 - 这不是生产代码。
Given a URL in a string:
http://www.example.com/test.xml
What's the easiest/most succinct way to download the contents of the file from the server (pointed to by the url) into a string in C#?
The way I'm doing it at the moment is:
WebRequest request = WebRequest.Create("http://www.example.com/test.xml");
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
That's a lot of code that could essentially be one line:
string responseFromServer = ????.GetStringFromUrl("http://www.example.com/test.xml");
Note: I'm not worried about asynchronous calls - this is not production code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
重要提示:这在编写时是正确的,但在
$current_year$
中,请参阅下面的HttpClient
答案Important: this was correct when written, but in
$current_year$
, please see theHttpClient
answer below上面答案中的方法现已弃用,当前建议使用 HttpClient:
The method in the above answer is now deprecated, the current recommendation is to use HttpClient:
鉴于,在撰写本文时,
HttpClient
是执行此功能的唯一剩余的、有效 .Net 机制,并且在任何情况下如果您“不担心异步调用”(这对于HttpClient
来说似乎是不可避免的),我认为这个函数应该可以满足您的需求:完成此操作后,任何时候您想通过简单的 URL+GET 查询来访问网站,您都可以简单地执行以下操作:
Given that, at the time of this writing,
HttpClient
is the only remaining, valid .Net mechanism for performing this function, and, in any case where you're "not worried about asynchronous calls" (which appear to be unavoidable withHttpClient
), I think that this function should get you what you're after:With that in place, anytime you want to interrogate a website with a simple URL+GET inquiry, you can simply do: