Friday, April 20, 2007

Get Web Page Contents in Code With C#

//The .NET framework provides a rich set of methods to access data stores on the web.

//Include right namespace.
using System;
using System.Text;
using System.Net;
using System.IO;


//The HttpWebRequest object allows us to create a request to URL.
//URL variable should contains the URL that you want to get.
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);
myRequest.Method = "GET";

//WebResponse allows us to read the response to the request.
WebResponse myResponse = myRequest.GetResponse();

//We will use StreamReader object to read the response into a string variables.
StreamReader rs = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);

//result variable will contain the contents of the Web page.
string result = sr.ReadToEnd();
sr.Close();
myResponse.Close();

//You may add some error handling as well for a real application.

No comments:

Labels

Blog Archive