首页 > Web开发 > 详细

警惕使用WebClient.DownloadFile(string uri,string filePath)方法

时间:2014-11-06 07:01:34      阅读:320      评论:0      收藏:0      [点我收藏+]
原文:警惕使用WebClient.DownloadFile(string uri,string filePath)方法

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();
    }
}

警惕使用WebClient.DownloadFile(string uri,string filePath)方法

原文:http://www.cnblogs.com/lonelyxmas/p/4077754.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!