Tuesday, 16 October 2012

Download a webpage in Asp.Net C#


First use the System.Net.WebRequestFactory class to acquire a WebRequest object:
WebRequest request = WebRequest.Create( "http://localhost" );
Then ask for the response from the request:
WebResponse response = request.GetResponse();
The GetResponse method blocks until the download is complete. Then you can access the response stream like this:
Stream s = response.GetResponseStream();

// Output the downloaded stream to the console
StreamReader sr = new StreamReader( s );
string line;
while( (line = sr.ReadLine()) != null )
Console.WriteLine( line );
Note that WebRequest and WebReponse objects can be downcast to HttpWebRequest and HttpWebReponse objects respectively, to access http-specific functionality

No comments:

Post a Comment