C# 利用SharpZipLib生成壓縮包

来源:https://www.cnblogs.com/hsiang/archive/2018/09/28/9721423.html
-Advertisement-
Play Games

本文通過一個簡單的小例子簡述SharpZipLib壓縮文件的常規用法,僅供學習分享使用,如有不足之處,還請指正。 ...


本文通過一個簡單的小例子簡述SharpZipLib壓縮文件的常規用法,僅供學習分享使用,如有不足之處,還請指正。

什麼是SharpZipLib ?

SharpZipLib是一個C#的類庫,主要用來解壓縮Zip,GZip,BZip2,Tar等格式,是以托管程式集的方式實現,可以方便的應用於其他的項目之中。

在工程中引用SharpZipLib

在項目中,點擊項目名稱右鍵-->管理NuGet程式包,打開NuGet包管理器視窗,進行搜索下載即可,如下圖所示:

SharpZipLib的關鍵類結構圖

如下所示:

涉及知識點:

  • ZipOutputStream 壓縮輸出流,將文件一個接一個的寫入壓縮文檔,此類不是線程安全的。
  • PutNextEntry 開始一個新的ZIP條目,ZipOutputStream中的方法。
  • ZipEntry 一個ZIP文件中的條目,可以理解為壓縮包裡面的一個文件夾/文件。
  • ZipInputStream 解壓縮輸出流,從壓縮包中一個接一個的讀出文檔。
  • GetNextEntry 讀出ZIP條目,ZipInputStream中的方法。

示例效果圖:

關於解壓縮小例子的示例效果圖,如下:

核心代碼

  1 using ICSharpCode.SharpZipLib.Checksum;
  2 using ICSharpCode.SharpZipLib.Zip;
  3 using System;
  4 using System.Collections.Generic;
  5 using System.IO;
  6 using System.Linq;
  7 using System.Text;
  8 using System.Threading.Tasks;
  9 
 10 namespace DemoZip
 11 {
 12     class ZipHelper
 13     {
 14         private string rootPath = string.Empty;
 15 
 16         #region 壓縮  
 17 
 18         /// <summary>   
 19         /// 遞歸壓縮文件夾的內部方法   
 20         /// </summary>   
 21         /// <param name="folderToZip">要壓縮的文件夾路徑</param>   
 22         /// <param name="zipStream">壓縮輸出流</param>   
 23         /// <param name="parentFolderName">此文件夾的上級文件夾</param>   
 24         /// <returns></returns>   
 25         private  bool ZipDirectory(string folderToZip, ZipOutputStream zipStream, string parentFolderName)
 26         {
 27             bool result = true;
 28             string[] folders, files;
 29             ZipEntry ent = null;
 30             FileStream fs = null;
 31             Crc32 crc = new Crc32();
 32 
 33             try
 34             {
 35                 string entName = folderToZip.Replace(this.rootPath, string.Empty)+"/";
 36                 //Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/")
 37                 ent = new ZipEntry(entName);
 38                 zipStream.PutNextEntry(ent);
 39                 zipStream.Flush();
 40 
 41                 files = Directory.GetFiles(folderToZip);
 42                 foreach (string file in files)
 43                 {
 44                     fs = File.OpenRead(file);
 45 
 46                     byte[] buffer = new byte[fs.Length];
 47                     fs.Read(buffer, 0, buffer.Length);
 48                     ent = new ZipEntry(entName + Path.GetFileName(file));
 49                     ent.DateTime = DateTime.Now;
 50                     ent.Size = fs.Length;
 51 
 52                     fs.Close();
 53 
 54                     crc.Reset();
 55                     crc.Update(buffer);
 56 
 57                     ent.Crc = crc.Value;
 58                     zipStream.PutNextEntry(ent);
 59                     zipStream.Write(buffer, 0, buffer.Length);
 60                 }
 61 
 62             }
 63             catch
 64             {
 65                 result = false;
 66             }
 67             finally
 68             {
 69                 if (fs != null)
 70                 {
 71                     fs.Close();
 72                     fs.Dispose();
 73                 }
 74                 if (ent != null)
 75                 {
 76                     ent = null;
 77                 }
 78                 GC.Collect();
 79                 GC.Collect(1);
 80             }
 81 
 82             folders = Directory.GetDirectories(folderToZip);
 83             foreach (string folder in folders)
 84                 if (!ZipDirectory(folder, zipStream, folderToZip))
 85                     return false;
 86 
 87             return result;
 88         }
 89 
 90         /// <summary>   
 91         /// 壓縮文件夾    
 92         /// </summary>   
 93         /// <param name="folderToZip">要壓縮的文件夾路徑</param>   
 94         /// <param name="zipedFile">壓縮文件完整路徑</param>   
 95         /// <param name="password">密碼</param>   
 96         /// <returns>是否壓縮成功</returns>   
 97         public  bool ZipDirectory(string folderToZip, string zipedFile, string password)
 98         {
 99             bool result = false;
100             if (!Directory.Exists(folderToZip))
101                 return result;
102 
103             ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipedFile));
104             zipStream.SetLevel(6);
105             if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
106 
107             result = ZipDirectory(folderToZip, zipStream, "");
108 
109             zipStream.Finish();
110             zipStream.Close();
111 
112             return result;
113         }
114 
115         /// <summary>   
116         /// 壓縮文件夾   
117         /// </summary>   
118         /// <param name="folderToZip">要壓縮的文件夾路徑</param>   
119         /// <param name="zipedFile">壓縮文件完整路徑</param>   
120         /// <returns>是否壓縮成功</returns>   
121         public  bool ZipDirectory(string folderToZip, string zipedFile)
122         {
123             bool result = ZipDirectory(folderToZip, zipedFile, null);
124             return result;
125         }
126 
127         /// <summary>   
128         /// 壓縮文件   
129         /// </summary>   
130         /// <param name="fileToZip">要壓縮的文件全名</param>   
131         /// <param name="zipedFile">壓縮後的文件名</param>   
132         /// <param name="password">密碼</param>   
133         /// <returns>壓縮結果</returns>   
134         public  bool ZipFile(string fileToZip, string zipedFile, string password)
135         {
136             bool result = true;
137             ZipOutputStream zipStream = null;
138             FileStream fs = null;
139             ZipEntry ent = null;
140 
141             if (!File.Exists(fileToZip))
142                 return false;
143 
144             try
145             {
146                 fs = File.OpenRead(fileToZip);
147                 byte[] buffer = new byte[fs.Length];
148                 fs.Read(buffer, 0, buffer.Length);
149                 fs.Close();
150 
151                 fs = File.Create(zipedFile);
152                 zipStream = new ZipOutputStream(fs);
153                 if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
154                 ent = new ZipEntry(Path.GetFileName(fileToZip));
155                 zipStream.PutNextEntry(ent);
156                 zipStream.SetLevel(6);
157 
158                 zipStream.Write(buffer, 0, buffer.Length);
159 
160             }
161             catch
162             {
163                 result = false;
164             }
165             finally
166             {
167                 if (zipStream != null)
168                 {
169                     zipStream.Finish();
170                     zipStream.Close();
171                 }
172                 if (ent != null)
173                 {
174                     ent = null;
175                 }
176                 if (fs != null)
177                 {
178                     fs.Close();
179                     fs.Dispose();
180                 }
181             }
182             GC.Collect();
183             GC.Collect(1);
184 
185             return result;
186         }
187 
188         /// <summary>   
189         /// 壓縮文件   
190         /// </summary>   
191         /// <param name="fileToZip">要壓縮的文件全名</param>   
192         /// <param name="zipedFile">壓縮後的文件名</param>   
193         /// <returns>壓縮結果</returns>   
194         public  bool ZipFile(string fileToZip, string zipedFile)
195         {
196             bool result = ZipFile(fileToZip, zipedFile, null);
197             return result;
198         }
199 
200         /// <summary>   
201         /// 壓縮文件或文件夾   
202         /// </summary>   
203         /// <param name="fileToZip">要壓縮的路徑</param>   
204         /// <param name="zipedFile">壓縮後的文件名</param>   
205         /// <param name="password">密碼</param>   
206         /// <returns>壓縮結果</returns>   
207         public  bool Zip(string fileToZip, string zipedFile, string password)
208         {
209             bool result = false;
210             if (Directory.Exists(fileToZip))
211             {
212                 this.rootPath = Path.GetDirectoryName(fileToZip);
213                 result = ZipDirectory(fileToZip, zipedFile, password);
214             }
215             else if (File.Exists(fileToZip))
216             {
217                 this.rootPath = Path.GetDirectoryName(fileToZip);
218                 result = ZipFile(fileToZip, zipedFile, password);
219             }
220             return result;
221         }
222 
223         /// <summary>   
224         /// 壓縮文件或文件夾   
225         /// </summary>   
226         /// <param name="fileToZip">要壓縮的路徑</param>   
227         /// <param name="zipedFile">壓縮後的文件名</param>   
228         /// <returns>壓縮結果</returns>   
229         public  bool Zip(string fileToZip, string zipedFile)
230         {
231             bool result = Zip(fileToZip, zipedFile, null);
232             return result;
233 
234         }
235 
236         #endregion
237 
238         #region 解壓  
239 
240         /// <summary>   
241         /// 解壓功能(解壓壓縮文件到指定目錄)   
242         /// </summary>   
243         /// <param name="fileToUnZip">待解壓的文件</param>   
244         /// <param name="zipedFolder">指定解壓目標目錄</param>   
245         /// <param name="password">密碼</param>   
246         /// <returns>解壓結果</returns>   
247         public bool UnZip(string fileToUnZip, string zipedFolder, string password)
248         {
249             bool result = true;
250             FileStream fs = null;
251             ZipInputStream zipStream = null;
252             ZipEntry ent = null;
253             string fileName;
254 
255             if (!File.Exists(fileToUnZip))
256                 return false;
257 
258             if (!Directory.Exists(zipedFolder))
259                 Directory.CreateDirectory(zipedFolder);
260 
261             try
262             {
263                 zipStream = new ZipInputStream(File.OpenRead(fileToUnZip));
264                 if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
265                 while ((ent = zipStream.GetNextEntry()) != null)
266                 {
267                     if (!string.IsNullOrEmpty(ent.Name))
268                     {
269                         fileName = Path.Combine(zipedFolder, ent.Name);
270                         fileName = fileName.Replace('/', '\\');//change by Mr.HopeGi   
271 
272                         if (fileName.EndsWith("\\"))
273                         {
274                             Directory.CreateDirectory(fileName);
275                             continue;
276                         }
277 
278                         fs = File.Create(fileName);
279                         int size = 2048;
280                         byte[] data = new byte[size];
281                         while (true)
282                         {
283                             size = zipStream.Read(data, 0, data.Length);
284                             if (size > 0)
285                                 fs.Write(data, 0, data.Length);
286                             else
287                                 break;
288                         }
289                     }
290                 }
291             }
292             catch
293             {
294                 result = false;
295             }
296             finally
297             {
298                 if (fs != null)
299                 {
300                     fs.Close();
301                     fs.Dispose();
302                 }
303                 if (zipStream != null)
304                 {
305                     zipStream.Close();
306                     zipStream.Dispose();
307                 }
308                 if (ent != null)
309                 {
310                     ent = null;
311                 }
312                 GC.Collect();
313                 GC.Collect(1);
314             }
315             return result;
316         }
317 
318         /// <summary>   
319         /// 解壓功能(解壓壓縮文件到指定目錄)   
320         /// </summary>   
321         /// <param name="fileToUnZip">待解壓的文件</param>   
322         /// <param name="zipedFolder">指定解壓目標目錄</param>   
323         /// <returns>解壓結果</returns>   
324         public bool UnZip(string fileToUnZip, string zipedFolder)
325         {
326             bool result = UnZip(fileToUnZip, zipedFolder, null);
327             return result;
328         }
329 
330         #endregion
331     }
332 }
View Code

備註

關於生成壓縮的方法還有很多,如通過命令行調用winrar的執行文件,SharpZipLib只是方法之一。

關於SharpZipLib的的API文檔,可參看鏈接

關於源碼下載鏈接


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 最近手上項目空了下來,沒什麼事做。博客博客不想寫,文章文章不想看。於是乾脆看點小說吧,但是上班時間,大家都在認認真真敲代碼,自己拿出手機看小說又不是很好(其實主要是數據線壞了,在公司沒發充電),電腦上瀏覽器看,更是不行。於是想了想,乾脆就自己爬著看吧,把內容列印在IDE的控制台,想一想這波操作就很騷 ...
  • 前言 正式開始Python之旅,主要學習內容專註在爬蟲和人工智慧領域,如Web開發之類將跳過不研究。 Python的意思是蟒蛇,源於作者Guido van Rossum(龜叔)喜歡的一部電視劇。所以現在開始暫時忘掉.NET忘掉C#,using乾什麼用的?不知道.... 我只記得、我要玩蛇!!! Py ...
  • 輸入兩棵二叉樹A,B,判斷B是不是A的子結構。(ps:我們約定空樹不是任意一個樹的子結構) 1.子樹的意思是包含了一個節點,就得包含這個節點下的所有節點,兩棵樹同時到底 2.子結構可以是A樹的任意一部分 思路: 1.第一個遞歸:A和B兩棵樹,先在A中找到與B的根結點相同的點,如果A的根不是,那就遞歸... ...
  • 迭代器 迭代就是重覆的一個過程,但是不是單純的重覆,每一次的重覆都是基於上一次的結果產生的。不過只記住迭代他就是重覆的執行過程就是了。 迭代器就是迭代取數的一個工具,關鍵是我們為什麼要用迭代器呢?我們都知道python中主要的一些數據類型有整型,字元串,元祖,列表,字典,集合,文件等。對於整型而言只 ...
  • 學習類的實例化的時候遇到了AttributeError: 'str' object has no attribute 'input_text', 以下是報錯的代碼及修改正確的代碼。 輸出結果: 請輸入一個數字:1Traceback (most recent call last): File "D:/ ...
  • Lingo安裝 Lingo簡介        LINGO是Linear Interactive and General Optimizer的縮寫,即“互動式的線性和通用優化求解器”,由美國LINDO系統公司(Lindo Syste ...
  • Spring Security的介紹就省略了,直接記錄一下登陸驗證授權的過程。 Spring Security的幾個重要詞 1.SecurityContextHolder:是安全上下文容器,可以在此得知操作的用戶是誰,該用戶是否已經被認證,他擁有哪些角色許可權…這些都被保存在SecurityConte ...
  • 隨機生成驗證碼,不能以圖片的形式存在,所以需要將驗證碼圖片以MemoryStream形式存儲在記憶體的流當中,但是在使用時發現使用PictureBox控制項無法顯示記憶體流,所以需要先將流轉化為圖片,才可以顯示,需要使用Bitmap類(System.Drawing.Bitmap)將記憶體流轉化為圖片的形式, ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...