super9
super9

Reputation: 30121

Output website X HTML to console in C#

Im in a middle of teaching myself to code so do pardon the ignorance.

So my question is, what do I need to read/learn in order to be able to output the HTML of a particular website (e.g google.com) to console?

Thanks.

Upvotes: 1

Views: 3899

Answers (5)

CodingGorilla
CodingGorilla

Reputation: 19842

I would suggest you start here: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest%28v=VS.90%29.aspx

Essentially, you create the HttpWebRequest and then call the GetResponse() method. You can then read the response stream and output it to your console.

Upvotes: 1

Pieter888
Pieter888

Reputation: 4992

This will do the trick:

WebClient client = new WebClient();
Stream data = client.OpenRead("www.google.com");
StreamReader reader = new StreamReader(data);
string str = reader.ReadLine();
Console.WriteLine(str);

Upvotes: 0

DarrellNorton
DarrellNorton

Reputation: 4661

Use HttpWebRequest to create a request and output the response to the console.

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

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
        public static void Main ()
        {
            // Create a request for the URL.        
            WebRequest request = WebRequest.Create ("http://www.contoso.com/default.html");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
            // Display the status.
            Console.WriteLine (response.StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream ();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader (dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd ();
            // Display the content.
            Console.WriteLine (responseFromServer);
            // Cleanup the streams and the response.
            reader.Close ();
            dataStream.Close ();
            response.Close ();
        }
    }
}

Upvotes: 1

Graham Clark
Graham Clark

Reputation: 12966

Have a look at the WebClient class, particularly the example at the bottom of the MSDN page.

Upvotes: 0

Lazarus
Lazarus

Reputation: 43084

Most browsers allow you to right-click and select "View Source", that's the easiest way to see the HTML.

Upvotes: 0

Related Questions