C# 从 URL 读取到 .NET 中的字符串的最简单方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1048199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Easiest way to read from a URL into a string in .NET
提问by rein
Given a URL in a string:
给定一个字符串中的 URL:
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#?
将文件内容从服务器(由 url 指向)下载到 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.
注意:我不担心异步调用 - 这不是生产代码。
采纳答案by Marc Gravell
using(WebClient client = new WebClient()) {
string s = client.DownloadString(url);
}