利用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; } } }