天天看点

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

C#使用WebClient下载文件到本地目录。

1、配置本地目录路径

<appSettings>
  <!--文件下载目录-->
  <add key="Download_Dic" value="E:\MyDownloadFile\"/>
</appSettings>
           

2、创建FileHandler.cs类,编写下载代码

/// <summary>
/// 文件处理类
/// </summary>
public static class FileHandler
{
    /// <summary>
    /// 文件下载目录
    /// </summary>
    private static string _directory = @ConfigurationSettings.AppSettings["Download_Dic"];

    /// <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);
            }
            WebClient client = new WebClient();
            client.DownloadFile(url, _directory + fileName);
            return fileName;
        }
        catch
        {
            return "";
        }
    }

    /// <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;
    }

}
           

3、调用测试

static void Main(string[] args)
{
    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();
}
           

继续阅读