SoFunction
Updated on 2025-03-01

C# to implement the method of downloading web HTML source code

This article describes the method of C# to download web HTML source code. Share it for your reference. The specific methods are as follows:

public static class DownLoad_HTML
{
private static int FailCount = 0; //Record the number of download failures
public static string GetHtml(string url) //Transfer to the URL to download{
string str = ;
try
{
 request = (url);
 = 10000; //Download timeout("Pragma", "no-cache");
 response = ();
 streamReceive = ();
Encoding encoding = ("gb2312");//utf-8 Web page text encoding streamReader = new (streamReceive, encoding);
str = ();
();
}
catch (Exception ex)
{
FailCount++;

if (FailCount > 5)
{
var result = ("Download failed" + FailCount + "Ship, do you want to continue trying?" +  + (), "Data download exception", , );
if (result == )
{
str = GetHtml(url);
}
else
{
("HTML download failed" +  + (), "HTML download failed", , );
throw ex;
}
}
else
{
str = GetHtml(url);
}
}

FailCount = 0; //If you can execute this step, it means that the download has finally succeededreturn str;
}

I hope this article will be helpful to everyone's C# programming