The easiest way to read from a URL to a string in .NET.

Given the URL in the line:

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

What is the easiest / shortest way to load the contents of a file from a server (with a URL) into a string in C #?

The way I'm doing it now 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(); 

This is a lot of code, which can essentially be a single line:

 string responseFromServer = ????.GetStringFromUrl("http://www.example.com/test.xml"); 

Note. Asynchronous calls don't bother me - this is not production code.

+94
c # networking
Jun 26 '09 at 9:26 a.m.
source share
1 answer
 using(WebClient client = new WebClient()) { string s = client.DownloadString(url); } 
+251
Jun 26 '09 at 9:27
source share



All Articles