Home >Backend Development >C++ >How to Download HTML Source Code in C#?

How to Download HTML Source Code in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-06 00:44:40320browse

How to Download HTML Source Code in C#?

Downloading HTML Source in C#

Problem:
How do you retrieve the HTML source code for a specific web address using C#?

Solution:
To download the HTML source code from a web address, you can utilize the WebClient class from the System.Net namespace.

Code Snippet:

using System.Net;

using (WebClient client = new WebClient())
{
    // Download the HTML code and save it to a local file
    client.DownloadFile("http://yoursite.com/page.html", @"C:\localfile.html");

    // Alternatively, you can retrieve the HTML code without saving it
    string htmlCode = client.DownloadString("http://yoursite.com/page.html");
}

In this code snippet, WebClient is inherited from IDisposable, ensuring that system resources are properly disposed after use. To download the HTML source, you specify the web address and the path where you want to save the downloaded file. Alternatively, you can directly retrieve the HTML code as a string without saving it locally.

The above is the detailed content of How to Download HTML Source Code in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn