Get Web Page Contents in Code with C#

Contributor Icon Contributed by johnnythawte Date Icon December 27, 2006  
Tag Icon Tagged: C programming

When you are developing an application that needs to access data stored on a web server, you can easily get the contents of a web page with this simple C# function.


The .NET framework provides a rich set of methods to access data stored on the web. First you will have to include the right namespaces:
using System.Text;
using System.Net;
using System.IO;

The HttpWebRequest object allows us to create a request to the URL, and the WebResponse allows us to read the response to the request.

We’ll use a StreamReader object to read the response into a string variable.

Here’s the actual code:

HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
sr.Close();
myResponse.Close();

In this code sample, the URL variable should contain the URL that you want to get, and the result variable will contain the contents of the web page. You may want to add some error handling as well for a real application.

Previous recipe | Next recipe |
 

 
close Reblog this comment
blog comments powered by Disqus