WebClient 輕鬆實現檔案下載上傳、網頁抓取

來源:互聯網
上載者:User
我們知道用 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/。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.