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
Here’s the ruby version:
require 'open-uri'puts open("http://www.helephant.com").read rescue puts "Error"
I think it speaks for itself :-)
:) each to their own.
Er, hrm. Sorry about that broken markup :-/
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.