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.cs686 chars27 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.
gistlibby LogSnag