警惕使用WebClient.DownloadFile(string uri,string filePath)方法
生活随笔
收集整理的這篇文章主要介紹了
警惕使用WebClient.DownloadFile(string uri,string filePath)方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
警惕使用WebClient.DownloadFile(string uri,string filePath)方法 原文:警惕使用WebClient.DownloadFile(string uri,string filePath)方法
{
????static?void?Main(string[]?args)
????{
????????const?string?filePath?=?@"c:\a.html";
????????const?string?url?=?"http://dat0a11.book.hexun.com/chapter-1031-1-7.shtml";
????????try
????????{
????????????using?(WebClient?wc?=?new?WebClient())
????????????{
????????????????//wc.DownloadFile("http://dat0a11.book.hexun.com/chapter-1031-1-7.shtml",?filePath);
????????????????string?html?=?wc.DownloadString(url);
????????????????using?(StreamWriter?writer?=?new?StreamWriter(filePath,false,wc.Encoding))
????????????????{
????????????????????writer.Write(html);
????????????????????writer.Flush();
????????????????}
????????????}
????????}
????????catch?(Exception?ex)
????????{
????????????Console.WriteLine(ex.Message);
????????}
????????Console.Read();
????}
} posted on 2014-11-06 02:15 NET未來之路 閱讀(...) 評論(...) 編輯 收藏
WebClient.DownloadFile(string uri,string filePath)方法用來請求一個url,并將請求內容存到本地的一個文件中。
使用這個方法,如果filePath是一個已經存在的文件,如果DownloadFile的執行web請求的過程中發生了錯誤,則會刪除掉filePath以前的內容。以下是驗證代碼,和另一種選擇方案。
?
class?Program{
????static?void?Main(string[]?args)
????{
????????const?string?filePath?=?@"c:\a.html";
????????const?string?url?=?"http://dat0a11.book.hexun.com/chapter-1031-1-7.shtml";
????????try
????????{
????????????using?(WebClient?wc?=?new?WebClient())
????????????{
????????????????//wc.DownloadFile("http://dat0a11.book.hexun.com/chapter-1031-1-7.shtml",?filePath);
????????????????string?html?=?wc.DownloadString(url);
????????????????using?(StreamWriter?writer?=?new?StreamWriter(filePath,false,wc.Encoding))
????????????????{
????????????????????writer.Write(html);
????????????????????writer.Flush();
????????????????}
????????????}
????????}
????????catch?(Exception?ex)
????????{
????????????Console.WriteLine(ex.Message);
????????}
????????Console.Read();
????}
} posted on 2014-11-06 02:15 NET未來之路 閱讀(...) 評論(...) 編輯 收藏
轉載于:https://www.cnblogs.com/lonelyxmas/p/4077754.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的警惕使用WebClient.DownloadFile(string uri,string filePath)方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: The Reflection And A
- 下一篇: MMORPG大型游戏设计与开发(part