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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM