警惕使用WebClient.DownloadFile(string uri,string filePath)方法
生活随笔
收集整理的這篇文章主要介紹了
警惕使用WebClient.DownloadFile(string uri,string filePath)方法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
警惕使用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未來(lái)之路 閱讀(...) 評(píng)論(...) 編輯 收藏
WebClient.DownloadFile(string uri,string filePath)方法用來(lái)請(qǐng)求一個(gè)url,并將請(qǐng)求內(nèi)容存到本地的一個(gè)文件中。
使用這個(gè)方法,如果filePath是一個(gè)已經(jīng)存在的文件,如果DownloadFile的執(zhí)行web請(qǐng)求的過程中發(fā)生了錯(cuò)誤,則會(huì)刪除掉filePath以前的內(nèi)容。以下是驗(yàn)證代碼,和另一種選擇方案。
?
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未來(lái)之路 閱讀(...) 評(píng)論(...) 編輯 收藏
轉(zhuǎn)載于:https://www.cnblogs.com/lonelyxmas/p/4077754.html
與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的警惕使用WebClient.DownloadFile(string uri,string filePath)方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: The Reflection And A
- 下一篇: MMORPG大型游戏设计与开发(part