Easiest way to read from a URL into a string in .NET

C#HttpNetworking

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

The method in the above answer is now deprecated, the current recommendation is to use HTTPClient:

    using (HttpClient client = new HttpClient())
    {
        string s = await client.GetStringAsync(url);
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionreinView Question on Stackoverflow
Solution 1 - C#Marc GravellView Answer on Stackoverflow
Solution 2 - C#PlasmaView Answer on Stackoverflow