• 使用WebClient下载文件到本地目录


    利用WebClient实现下载文件

    调用

     string url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1494677827304&di=8e8aaf1a717ae37b73b772ee4728c7ea&imgtype=0&src=http%3A%2F%2Fscimg.jb51.net%2Fallimg%2F141123%2F10-1411231F92W16.jpg";
                string fileName = FileHandler.DownloadFile(url);
                if (!String.IsNullOrEmpty(fileName))
                {
                    Console.WriteLine("文件下载成功,文件名称:" + fileName);
                }
                else
                {
                    Console.WriteLine("文件下载失败");
                }
                Console.ReadLine();
     /// <summary>
        /// 文件处理类
        /// </summary>
        public static class FileHandler
        {
            /// <summary>
            /// 文件下载目录
            /// </summary>
            private static string _directory = Path.Combine("C:\","Down\");//下载的文件存放于c盘Down文件夹下面
    
            /// <summary>
            /// 下载文件
            /// </summary>
            /// <param name="url">下载地址</param>
            /// <returns>文件名称</returns>
            public static string DownloadFile(string url)
            {
                try
                {
                    string fileName = CreateFileName(url);
                    if (!Directory.Exists(_directory))
                    {
                        Directory.CreateDirectory(_directory);
                    }
                    bool flag = url.StartsWith("http://") || url.StartsWith("https://");
                    if (flag)
                    {
                        WebClient client = new WebClient();
                        client.DownloadFile(url, _directory + fileName);
                    }                             
                    return fileName;
                }
                catch(Exception ex)
                {
                    throw ex;
                }
            }
    
            /// <summary>
            /// 创建文件名称
            /// </summary>
            public static string CreateFileName(string url)
            {
                string fileName = "";
                string fileExt = url.Substring(url.LastIndexOf(".")).Trim().ToLower();
                Random rnd = new Random();
                fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + rnd.Next(10, 99).ToString() + fileExt;
                return fileName;
            }
        }
        }
  • 相关阅读:
    easyExcel入门
    UML-从需求到设计--迭代进化
    UML-操作契约总结
    102. Binary Tree Level Order Traversal
    98. Validate Binary Search Tree
    95. Unique Binary Search Trees II
    96. Unique Binary Search Trees
    94. Binary Tree Inorder Traversal
    84. Largest Rectangle in Histogram
    92. Reverse Linked List II
  • 原文地址:https://www.cnblogs.com/macT/p/11394867.html
Copyright © 2020-2023  润新知