我們知道用 WebRequest(HttpWebRequest、FtpWebRequest) 和 WebResponse(HttpWebResponse、FtpWebResponse)可以實現檔案下載上傳、網頁抓取,可是用 WebClient 更輕鬆。用 DownloadFile 下載網頁using (System.Net.WebClient client = new System.Net.WebClient()){ client.DownloadFile("http://www.cftea.com/", "C:\\foo.txt");}就這樣,http://www.cftea.com/ 首頁就被儲存到 C 盤下了。用 DownloadData 或 OpenRead 抓取網頁using (System.Net.WebClient client = new System.Net.WebClient()){ byte[] bytes = client.DownloadData("http://www.cftea.com/"); string str = (System.Text.Encoding.GetEncoding("gb2312").GetString(bytes);}我們將抓取來的網頁賦給變數 str,任由我們使用。也可以用 OpenRead 方法來擷取資料流。using (System.Net.WebClient client = new System.Net.WebClient()){ using (System.IO.Stream stream = client.OpenRead("http://www.cftea.com/")) { using (System.IO.StreamReader reader = new System.IO.StreamReader(stream, System.Text.Encoding.GetEncoding("gb2312"))) { string str = reader.ReadToEnd(); reader.Close(); } stream.Close(); }}用 UploadFile 上傳檔案相對於 DownloadData、OpenRead,WebClient 也具有 UploadData、OpenWrite 方法,但最常用的恐怕還是上傳檔案,也就是用方法 UploadFile。using (System.Net.WebClient client = new System.Net.WebClient()){ client.Credentials = new System.Net.NetworkCredential("使用者名稱", "密碼"); client.UploadFile("ftp://www.cftea.com/foo.txt", "C:\\foo.txt");}注意 UploadFile 的第一個參數,要把上傳後形成的檔案名稱加上去,也就是說這裡不能是:ftp://www.cftea.com/。