Night | Snow

Get the content of an url in C#

Posted on: December 8th, 2009

Tags: ,

This is a easy way to get the content of a url into a string. You only need to open a new connection using HttpWebRequest, make a request and read the stream into a string. see the example below:

using System;
using System.Net;
using System.IO;

class functions
{
  public static String GetUrlContent(String Url)
  {
      // Open a connection
      HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(Url);
         
      // Specify header information like
      hwr.UserAgent = "simra.ch GetUrlContent";
      hwr.Referer = "http://www.simra.ch/";
         
      // Get the Request
      WebResponse wr = hwr.GetResponse();
         
      // Open a new Stream
      Stream ws = wr.GetResponseStream();
         
      // Create a SteamReader
      StreamReader sr = new StreamReader(ws);
         
      // Read the stream
      String content = sr.ReadToEnd();
         
      // Cleanup
      sr.Close();
      ws.Close();
      wr.Close();

      return content;
  }
}

News

Martin Fischer said:

Client and partner of simra.ch

Wir können Simon Schärer als kompetenter und zuverlässiger Programmierer höchst weiterempfehlen. Er ist nicht nur ein guter Programmierer, sondern auch ein ausgezeichneter Designer.
Danke Developer’s Island

Follow us on Twitter

favorite

I get asked a lot - which SDK should we use for web programming? I recommend Netbeans

my toolbar

Simra GameMP3 playersubscribe to RSSMy delicious bookmarksFacebookTwitterE-mail

No Responses to “Get the content of an url in C#”

RSS Feed Icon  Subscribe to comments follow-up

Trackbacks/Pingbacks

Leave a reply

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Latest Tweet

loading...