从 URL 读取到 .NET 中的字符串的最简单方法

问题描述:

给定一个字符串中的 URL:

Given a URL in a string:

http://www.example.com/test.xml

将文件内容从服务器(由 url 指向)下载到 C# 中的字符串的最简单/最简洁的方法是什么?

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#?

我目前的做法是:

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.

using(WebClient client = new WebClient()) {
   string s = client.DownloadString(url);
}