今天主要記錄、分享 使用WebClient 下載/獲取 文件的兩種方式。
話不多說,放置代碼。
第一種:使用 WebClient 自封裝方法: DownloadFile(); 下載方便、直接。
/// <summary> /// 下載文件(WebClient.DownloadFile) /// </summary> /// <param name="downFileUrl">下載文件鏈接地址</param> /// <param name="savePath">保存路徑</param> /// <returns></returns> public static string DownLoadFileByWebClientStatic(string downFileUrl, string savePath) { string result = string.Empty; try { WebClient wcClient = new WebClient(); wcClient.DownloadFile(downFileUrl, savePath); result = "下載成功"; } catch (WebException ex) { result = $"下載失敗!Error={ ex.Message}"; } return result; } /// <summary> /// 下載文件(wcClient.DownloadFileAsync) /// </summary> /// <param name="downFileUrl">下載文件鏈接地址</param> /// <param name="savePath">保存路徑</param> /// <returns></returns> public static string DownLoadFileMethod(string downFileUrl, string savePath) { string result = string.Empty; try { WebClient wcClient = new WebClient(); wcClient.DownloadDataCompleted += (t, s) => { result = "下載成功";//不會直接返回(無狀態?) }; wcClient.DownloadFileAsync(new Uri(downFileUrl), savePath); } catch (WebException ex) { result = $"下載失敗!Error={ ex.Message}"; } return result; }
第二種:使用讀取文件流形式下載/獲取文件。(自測通過)
/// <summary> /// 下載文件(Stream 形式處理) /// </summary> /// <param name="downFileUrl">下載文件鏈接地址</param> /// <param name="savePath">保存路徑</param> /// <returns></returns> public static string DownLoadFileByWebClient(string downFileUrl, string savePath) { string result = string.Empty; try { WebClient wcClient = new WebClient(); WebRequest webReq = WebRequest.Create(downFileUrl); WebResponse webRes = webReq.GetResponse(); long fileLength = webRes.ContentLength; Stream srm = webRes.GetResponseStream(); StreamReader srmReader = new StreamReader(srm); byte[] bufferbyte = new byte[fileLength]; int allByte = (int)bufferbyte.Length; int startByte = 0; while (fileLength > 0) { int downByte = srm.Read(bufferbyte, startByte, allByte); if (downByte == 0) break; startByte += downByte; allByte -= downByte; } //檢測保存文件所在目錄是否存在 if (!File.Exists(savePath)) { string[] dirArray = savePath.Split('\\'); string temp = string.Empty; for (int i = 0; i < dirArray.Length - 1; i++) { temp += dirArray[i].Trim() + "\\"; if (!Directory.Exists(temp)) Directory.CreateDirectory(temp); } } using (FileStream fsSave = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write)) { fsSave.Write(bufferbyte, 0, bufferbyte.Length); fsSave.Dispose(); } //與using 方法兩者等同。 //FileStream fs = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write); //fs.Write(bufferbyte, 0, bufferbyte.Length); srm.Close(); srmReader.Close(); //fs.Close(); result = $"下載成功 path={savePath}"; } catch (WebException ex) { result = $"下載失敗!Error={ ex.Message}"; } return result; }
第二種 通過文件流 下載,方法分支:(使用WebClient 的 OpenRead() 方式獲取到Stream ,然后進行文件流讀取,不知為何,自測失敗,下載的文件無法正常打開)。 現在還沒有找到合理解釋,希望大家評論。
/// <summary> /// 下載文件 /// </summary> /// <param name="URLAddress">資源URL</param> /// <param name="saveBasePath">保存根目錄/目錄</param> /// <returns></returns> public string DownFileByStream(string URLAddress, string saveBasePath) { string result = string.Empty; try { WebClient client = new WebClient(); Stream str = client.OpenRead(URLAddress); StreamReader reader = new StreamReader(str); byte[] bytes = new byte[1024 * 1024];//自定義大小 1M int allybytes = (int)bytes.Length; int startbytes = 0; while (allybytes > 0) { int m = str.Read(bytes, startbytes, allybytes); //獲取當前讀取字節位置 if (m == 0) break; startbytes += m; allybytes -= m; } reader.Dispose(); str.Dispose(); string path = saveBasePath + System.IO.Path.GetFileName(URLAddress); FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); fsWrite.Write(bytes, 0, startbytes); fsWrite.Flush(); fsWrite.Close(); result = "下載成功!"; } catch (Exception ex) { result = "下載失敗!" + ex.Message; } return result; }
如有不合理之處,歡迎指出。以上就是今天的記錄;本文大部分內容都可以搜到,只是此處做了一個小整理。
如果您覺得本文對您有幫助,歡迎點擊“收藏”按鈕!(/:微笑)歡迎轉載,轉載請注明出處。