參考代碼:
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; } } }
