Posted: 3 years ago

Filed under: .NET

Tagged with: c#

Follow comments

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.

Comments

  1. nornagon Says:

    Here’s the ruby version:

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

    I think it speaks for itself :-)

  2. Helen Says:

    :) each to their own.

  3. nornagon Says:

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

  4. Helen Says:

    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.

Leave a Reply