【C#】Get the html code of a webpage

时间:2021-02-20 17:23:04

As for the title,the console program will show you a sample which can get the webpage-code.Enjoy it:)

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Runtime.InteropServices; //dllimport relies on it
namespace WebPageCode
{ class Program
{ [DllImport("kernel32.dll")]
static extern uint GetTickCount(); static void addhead(ref string px) //add http head if necessary
{
if (px.Substring(, ).ToLower() != @"http://") px = @"http://" + px;
} static string getwebcode(string PageUrl,string proxy=""){ uint x = GetTickCount(); addhead(ref PageUrl); //webpage check
WebClient wc = new WebClient();
wc.Credentials = CredentialCache.DefaultCredentials; proxy.Trim(); //proxy check
if (proxy != "")
{
addhead(ref proxy);
WebProxy wp = new WebProxy();
wp.Address = new Uri(proxy);
wc.Proxy = wp;
} Byte[] pageData = wc.DownloadData(PageUrl);
x = GetTickCount() - x; //x means the time spent.
return Encoding.UTF8.GetString(pageData); } static void Main(string[] args)
{
int i = , n = args.Length;
string proxy = "";
string page = "";
while (i < n)
{
if (args[i] == "-proxy")
{
if (i<(n-)) proxy = args[++i];
}
if (args[i] == "-page")
{
if (i < (n - )) page = args[++i];
}
i++;
}
page.Trim(); proxy.Trim();
if (page == "") return; //no webpage found
string code;
if (proxy == ""){
code=getwebcode(page); //proxy found
} else {
code=getwebcode(page,proxy); //no proxy found
} Console.Write(code);
Console.ReadKey();
}
}
}