欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现下载网页HTML源码的方法

程序员文章站 2023-12-16 22:42:16
本文实例讲述了c#实现下载网页html源码的方法。分享给大家供大家参考之用。具体方法如下: public static class download_html...

本文实例讲述了c#实现下载网页html源码的方法。分享给大家供大家参考之用。具体方法如下:

public static class download_html
{
private static int failcount = 0; //记录下载失败的次数

public static string gethtml(string url) //传入要下载的网址
{
string str = string.empty;
try
{
system.net.webrequest request = system.net.webrequest.create(url);
request.timeout = 10000; //下载超时时间
request.headers.set("pragma", "no-cache");
system.net.webresponse response = request.getresponse();
system.io.stream streamreceive = response.getresponsestream();
encoding encoding = encoding.getencoding("gb2312");//utf-8 网页文字编码
system.io.streamreader streamreader = new system.io.streamreader(streamreceive, encoding);
str = streamreader.readtoend();
streamreader.close();
}
catch (exception ex)
{
failcount++;

if (failcount > 5)
{
var result = system.windows.forms.messagebox.show("已下载失败" + failcount + "次,是否要继续尝试?" + environment.newline + ex.tostring(), "数据下载异常", system.windows.forms.messageboxbuttons.yesno, system.windows.forms.messageboxicon.error);
if (result == system.windows.forms.dialogresult.yes)
{
str = gethtml(url);
}
else
{
system.windows.forms.messagebox.show("下载html失败" + environment.newline + ex.tostring(), "下载html失败", system.windows.forms.messageboxbuttons.ok, system.windows.forms.messageboxicon.error);
throw ex;
}
}
else
{
str = gethtml(url);
}
}

failcount = 0; //如果能执行到这一步就表示下载终于成功了
return str;
}

希望本文所述对大家的c#程序设计有所帮助

上一篇:

下一篇: