C#完成下載網頁HTML源碼的辦法。本站提示廣大學習愛好者:(C#完成下載網頁HTML源碼的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成下載網頁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#法式設計有所贊助