C# 从服务器下载文件并保存到客户端

参考代码:

using System;
using System.Net;

namespace HT.SIHONG.Common.Utility
{
    public class DownloadFile
    {
        /// <summary>
        /// 下载服务器文件并保存到客户端
        /// </summary>
        /// <param name="uri">被下载的文件地址,如:文件路径、url地址、ftp地址(包含文件名)</param>
        /// <param name="savePath">存放的目录(不包含文件名)</param>
        public static bool Download(string uri, string savePath)
        {
            //从文件路径中获取文件名
            string fileName;
            if (uri.IndexOf("\") > -1)
            {
                fileName = uri.Substring(uri.LastIndexOf("\") + 1);
            }
            else
            {
                fileName = uri.Substring(uri.LastIndexOf("/") + 1);
            }

            //设置文件保存路径:路径+""+文件名.后缀、路径+"/"+文件名.后缀
            if (!savePath.EndsWith("/") && !savePath.EndsWith("\"))
            {
                savePath = savePath + "/"; //也可以是savePath + "\"
            }

            savePath += fileName;   //另存为的绝对路径+文件名

            //下载文件
            WebClient client = new WebClient();
            try
            {
                client.DownloadFile(uri, savePath);
            }
            catch(Exception ex)
            {
                Logger.Error(typeof(DownloadFile), "下载文件失败", ex);
                return false;
            }

            return true;
        }
    }
}
原文地址:https://www.cnblogs.com/hellowzl/p/8042088.html