Read source of a web page in C#

This example shows how to read the source of a web page in C#.

// used to build entire input
StringBuilder sb = new StringBuilder();
 
// used on each read operation
byte[] buf = new byte[8192];
 
// prepare the web page we will be asking for
WebRequest request  = WebRequest.Create("http://andrewbeaton.com");
 
// execute the request
WebResponse response = request.GetResponse();
 
// we will read data via the response stream
Stream resStream = response.GetResponseStream();
 
string tempString = null;
int count = 0;
 
do
{
    // fill the buffer with data
    count = resStream.Read(buf, 0, buf.Length);
 
    // make sure we read some data
    if (count != 0) 
    {
        // translate from bytes to ASCII text
        tempString = Encoding.ASCII.GetString(buf, 0, count);
 
        // continue building the string
       sb.Append(tempString);
    }
}
while (count > 0);

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">