Accessing the contents of a URL through C#

Here’s a quick code snippet for accessing the contents of a url through C#.

It’s nice and straight forward. You just need to use the HttpWebRequest and HttpWebResponse System.Net classes to request the url and then a StreamReader to grab the text from the response’s stream.

The code should look something like this:

HttpWebRequest request = (HttpWebRequest) WebRequest.Create("");
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK &&
    response.ContentLength > 0){
    TextReader reader = new StreamReader(response.GetResponseStream());
    string text = reader.ReadToEnd();

See it working in a sample project.

Posted on 19 Aug 07 by Helen Emerson (last updated on 19 Aug 07).
Filed under .NET