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("http://www.helephant.com");
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK &&
    response.ContentLength > 0){
    TextReader reader = new StreamReader(response.GetResponseStream());
    string text = reader.ReadToEnd();
    Console.Write(text);
}

See it working in a sample project.

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

Comments

nornagon 20 Aug 2007

Here’s the ruby version:

require 'open-uri'
puts open("http://www.helephant.com").read rescue puts "Error"

I think it speaks for itself :-)

Helen 20 Aug 2007

:) each to their own.

nornagon 20 Aug 2007

Er, hrm. Sorry about that broken markup :-/

Helen 26 Aug 2007

I’m a bit paranoid about HTML in comments. Easiest to just strip it all out.

I’m quite interested in learning about Ruby on Rails. I’ll have to get you to tell me about it next time I see you in Sine.