WebClient是C# System.Net下的常用类,用于请求URI标识的资源,如http、https、ftp、file等,常用方法有OpenWrite、UploadData、UploadFile、UploadValues、DownloadData、DownloadFile、OpenRead等。
本文利用WebClient做了一个实例,用来查看网页源码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnGet_Click(object sender, EventArgs e)
{
string url = this.textUrl.Text.Trim();
if (string.IsNullOrEmpty(url))
MessageBox.Show("要获取的URL地址不能为空!");
else
{
if (!url.ToLower().StartsWith("http://") && !url.ToLower().StartsWith("https://"))
url = "http://" + url;
WebClient webClient = new WebClient();
Uri uri = new Uri(url);
Stream data = webClient.OpenRead(uri);
StreamReader streamReader;
if (radioButton1.Checked)
streamReader = new StreamReader(data, Encoding.UTF8);
else
streamReader = new StreamReader(data, Encoding.Default);
this.txtContent.Text = streamReader.ReadToEnd();

}
}
}
}

C#使用WebClient查看网页源码_.net