get web page source code in csharp

To get the source code of a web page in C#, we can make use of the HttpClient class from the System.Net.Http namespace. Here's a code snippet that demonstrates how to do it:

main.cs
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string url = "https://www.example.com";

        using (var client = new HttpClient())
        {
            try
            {
                HttpResponseMessage response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"Error: {e.Message}");
            }
        }
    }
}
686 chars
27 lines

In the code above, we first create a new HttpClient instance. We then call its GetAsync method, passing the URL of the web page we want to retrieve. This method returns an HttpResponseMessage object, which contains the response from the server.

We then call the EnsureSuccessStatusCode method to ensure that the response we received indicates success (i.e., the status code is in the 200-299 range).

Finally, we call the ReadAsStringAsync method of the response's Content property to get the HTML source code of the web page as a string. We then output this string to the console.

related categories

gistlibby LogSnag