1. 程式人生 > 實用技巧 >20200728-直接提取壓縮包裡的檔案

20200728-直接提取壓縮包裡的檔案

一 使用背景:

通過Http 請求下載一個壓縮的檔案到伺服器記憶體中(重點:不用儲存到本地),然後通過程式碼直接提取壓縮包的檔案

二 實現思路:(注:需要提前安裝 ICSharpCode.SharpZipLib.dll)

1 通過Http請求下載壓縮檔案到伺服器的記憶體中

2 讀取記憶體中壓縮的包的流(注意先將:Stream 轉換成MemoryStream)

3 通過ICSharpCode.SharpZipLib.Zip.dll的ZipFile方法將壓縮包的MemoryStream 注入

4 通過檔案索引提取壓縮包裡的檔案流

5 儲存上傳檔案到指定位置

三 參考程式碼:

 1         public
string HttpDownloadFile(int tenantId, RequestHeaadModel heaadModel) 2 { 3 var dfsResultPath = string.Empty; 4 var listDfsPath = new List<string>(); 5 try 6 { 7 #region Http請求引數設定 8 ServicePointManager.Expect100Continue = false
; 9 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; 10 ServicePointManager.ServerCertificateValidationCallback += (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => true
; 11 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(heaadModel.ResquestParamUrl); 12 request.Headers.Add("x-qys-accesstoken", heaadModel.Accesstoken); 13 request.Headers.Add("x-qys-timestamp", "0"); 14 request.Headers.Add("x-qys-signature", heaadModel.Searect); 15 request.ContentType = heaadModel.ContentType; 16 request.Method = "GET"; 17 request.Timeout = 100000; 18 request.Accept = "application/octet-stream"; 19 #endregion 20 21 #region 對響應的壓縮包解析 22 using (WebResponse webRes = request.GetResponse()) 23 { 24 #region 1 獲取響應的壓縮包檔案流 25 var length = (long)webRes.ContentLength; 26 var response = webRes as HttpWebResponse; 27 var stream = response.GetResponseStream(); 28 #endregion 29 30 #region 2 將壓縮包檔案流程讀取到記憶體中 31 var stmMemory = new MemoryStream(); 32 if (length == -1) 33 { 34 length = 1024; 35 } 36 var buffer = new byte[length]; 37 int i; 38 while ((i = stream.Read(buffer, 0, buffer.Length)) > 0) 39 { 40 stmMemory.Write(buffer, 0, i); 41 } 42 #endregion 43 44 #region 3 迴圈讀取壓縮包的檔案 45 var zipFile_ = new ICSharpCode.SharpZipLib.Zip.ZipFile(stmMemory); 46 int count = int.Parse(zipFile_.Count.ToString());//獲取檔案個數 47 for (int j = 0; j < count; j++) 48 { 49 var tempSteam = zipFile_.GetInputStream(long.Parse($"{i}"));//壓縮包裡的檔案索引 50 var stmMemory2 = new MemoryStream(); 51 var buffer2 = new byte[zipFile_[i].Size]; 52 int m; 53 //將單個檔案的檔案流讀取到記憶體中 54 while ((m = tempSteam.Read(buffer2, 0, buffer2.Length)) > 0) 55 { 56 stmMemory2.Write(buffer2, 0, m); 57 } 58 stmMemory2.Seek(0, SeekOrigin.Begin); 59 var dfsItem = new DfsItem("TenantBaseFile", zipFile_[i].Name, 60 stmMemory2, tenantId); 61 var dfsPath = Dfs.Store(dfsItem); 62 63 Logger.Debug($"下載背調檔案地址:{dfsPath.ToString()}"); 64 listDfsPath.Add(dfsPath.ToString()); 65 stmMemory2.Close(); 66 stmMemory2.Flush(); 67 } 68 #endregion 69 stmMemory.Close(); 70 stmMemory.Flush(); 71 } 72 #endregion 73 } 74 catch (Exception ex) 75 { 76 Logger.Debug($"下載報告異常:異常資訊:{ex.Message},堆疊資訊:{ex.StackTrace}"); 77 } 78 79 return string.Join(",", listDfsPath); 80 }
View Code