125

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.

rein
  • 32,067
  • 23
  • 80
  • 106

2 Answers2

297
using(WebClient client = new WebClient()) {
   string s = client.DownloadString(url);
}
Tim Cooper
  • 151,519
  • 37
  • 317
  • 271
Marc Gravell
  • 976,458
  • 251
  • 2,474
  • 2,830
  • Another one of those often-overlooked utility classes - but **so** useful. – Marc Gravell Jun 26 '09 at 09:31
  • 2
    Keep in mind that you should be putting it in a `try catch` block as well, in case something goes awry – mikeyq6 Aug 17 '15 at 16:02
  • @DanW yes it does, I've just tested it (with `string s = client.DownloadString("https://stackoverflow.com/questions/1048199/easiest-way-to-read-from-a-url-into-a-string-in-net/1048204");`) - works absolutely fine. Whatever is happening: it isn't https that is the immediate problem. Are you sure the site has a valid cert? – Marc Gravell May 13 '19 at 07:14
2

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);
    }
Plasma
  • 2,004
  • 2
  • 18
  • 32