C#獲取網(wǎng)頁HTML源碼實例
本文實例講述了C#獲取網(wǎng)頁HTML源碼的方法,分享給大家供大家參考。具體方法如下:
關(guān)鍵代碼如下:
/// 獲取網(wǎng)頁HTML源碼
/// </summary>
/// <param name="url">鏈接 eg:http://www.baidu.com/ </param>
/// <param name="charset">編碼 eg:Encoding.UTF8</param>
/// <returns>HTML源碼</returns>
public static string GetHtmlSource(string url, Encoding charset)
{
string _html = string.Empty;
try
{
HttpWebRequest _request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse _response = (HttpWebResponse)_request.GetResponse();
using (Stream _stream = _response.GetResponseStream())
{
using (StreamReader _reader = new StreamReader(_stream, charset))
{
_html = _reader.ReadToEnd();
}
}
}
catch (WebException ex)
{
using (StreamReader sr = new StreamReader(ex.Response.GetResponseStream()))
{
_html = sr.ReadToEnd();
}
}
catch (Exception ex)
{
_html = ex.Message;
}
return _html;
}
測試代碼如下:
{
string _url = "http://www.baidu.com/";
string _htmlSource = HttpWebRequestUtilsV2.GetHtmlSource(_url, Encoding.UTF8);
Console.WriteLine(_htmlSource);
}
測試效果如下圖所示:
希望本文所述對大家的C#程序設(shè)計有所幫助

C#實現(xiàn)對文件進(jìn)行加密保護(hù)的示例代碼

C#利用WMI操作DNS服務(wù)器(可遠(yuǎn)程操作,需要相應(yīng)權(quán)限)