Wednesday 26 November 2008

Best method to read a web page into a string in C#

There are a number of ways to get the contents of a web page (or xml document such as an RSS feed) into a string in C#.

Unless someone can show me an even shorter method, I think the least lines of code way to do this is using the WebClient class in the System.Net namespace as follows:

WebClient client = new WebClient();
string pageContents = client.DownloadString(url);

Job done!

Note that this is much shorter than the method you're most likely to find on Google which is to build a web request then process the resulting response stream into a string using a StreamReader as in the below example. This works but is a lot more lines of code and creation of unnecessary objects.

using System;
using System.IO;
using System.Net;
using System.Text;

public static void GetFile(string strURL, string strFilePath)
{
WebRequest myWebRequest = WebRequest.Create(strURL);
WebResponse myWebResponse = myWebRequest.GetResponse();

Stream ReceiveStream = myWebResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream =
new StreamReader( ReceiveStream, encode );
string strResponse = readStream.ReadToEnd();

readStream.Close();
myWebResponse.Close();

}

No comments: