zoukankan      html  css  js  c++  java
  • 警惕使用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();
        }
    }
  • 相关阅读:
    什么是Code Review
    支撑5亿用户、1.5亿活跃用户的Twitter最新架构详解及相关实现
    shell的数组操作
    CDN(内容分发网络)技术原理
    云计算服务模型,第 3 部分: 软件即服务(PaaS)
    Mongodb
    360的开源项目
    用linux mail命令发送邮件[Linux]
    BZOJ2761:[JLOI2011]不重复数字(map)
    BZOJ1821:[JSOI2010]部落划分(并查集,二分)
  • 原文地址:https://www.cnblogs.com/yukaizhao/p/webclient_downloadfile.html
Copyright © 2011-2022 走看看