C# 文件/文件夾壓縮解壓縮

来源:https://www.cnblogs.com/hahahayang/archive/2019/01/19/hahahayang.html
-Advertisement-
Play Games

項目上用到的,隨手做個記錄,哈哈。 直接上代碼: 1 using System; 2 using System.Data; 3 using System.Configuration; 4 using System.Collections.Generic; 5 using System.IO; 6 u ...


項目上用到的,隨手做個記錄,哈哈。

直接上代碼:

  1 using System;
  2 using System.Data;
  3 using System.Configuration;
  4 using System.Collections.Generic;
  5 using System.IO;
  6 using ICSharpCode.SharpZipLib.Zip;
  7 using ICSharpCode.SharpZipLib.Checksums;
  8 namespace BLL
  9 {
 10     /// <summary>  
 11     /// 文件(夾)壓縮、解壓縮  
 12     /// </summary>  
 13     public class FileCompression
 14     {
 15         #region 壓縮文件
 16         /// <summary>    
 17         /// 壓縮文件    
 18         /// </summary>    
 19         /// <param name="fileNames">要打包的文件列表</param>    
 20         /// <param name="GzipFileName">目標文件名</param>    
 21         /// <param name="CompressionLevel">壓縮品質級別(0~9)</param>    
 22         /// <param name="deleteFile">是否刪除原文件</param>  
 23         public static void CompressFile(List<FileInfo> fileNames, string GzipFileName, int CompressionLevel, bool deleteFile)
 24         {
 25             ZipOutputStream s = new ZipOutputStream(File.Create(GzipFileName));
 26             try
 27             {
 28                 s.SetLevel(CompressionLevel);   //0 - store only to 9 - means best compression    
 29                 foreach (FileInfo file in fileNames)
 30                 {
 31                     FileStream fs = null;
 32                     try
 33                     {
 34                         fs = file.Open(FileMode.Open, FileAccess.ReadWrite);
 35                     }
 36                     catch
 37                     { continue; }
 38                     //  方法二,將文件分批讀入緩衝區    
 39                     byte[] data = new byte[2048];
 40                     int size = 2048;
 41                     ZipEntry entry = new ZipEntry(Path.GetFileName(file.Name));
 42                     entry.DateTime = (file.CreationTime > file.LastWriteTime ? file.LastWriteTime : file.CreationTime);
 43                     s.PutNextEntry(entry);
 44                     while (true)
 45                     {
 46                         size = fs.Read(data, 0, size);
 47                         if (size <= 0) break;
 48                         s.Write(data, 0, size);
 49                     }
 50                     fs.Close();
 51                     if (deleteFile)
 52                     {
 53                         file.Delete();
 54                     }
 55                 }
 56             }
 57             finally
 58             {
 59                 s.Finish();
 60                 s.Close();
 61             }
 62         }
 63         /// <summary>    
 64         /// 壓縮文件夾    
 65         /// </summary>    
 66         /// <param name="dirPath">要打包的文件夾</param>    
 67         /// <param name="GzipFileName">目標文件名</param>    
 68         /// <param name="CompressionLevel">壓縮品質級別(0~9)</param>    
 69         /// <param name="deleteDir">是否刪除原文件夾</param>  
 70         public static void CompressDirectory(string dirPath, string GzipFileName, int CompressionLevel, bool deleteDir)
 71         {
 72             //壓縮文件為空時預設與壓縮文件夾同一級目錄    
 73             if (GzipFileName == string.Empty)
 74             {
 75                 GzipFileName = dirPath.Substring(dirPath.LastIndexOf("//") + 1);
 76                 GzipFileName = dirPath.Substring(0, dirPath.LastIndexOf("//")) + "//" + GzipFileName + ".zip";
 77             }
 78             //if (Path.GetExtension(GzipFileName) != ".zip")  
 79             //{  
 80             //    GzipFileName = GzipFileName + ".zip";  
 81             //}  
 82             using (ZipOutputStream zipoutputstream = new ZipOutputStream(File.Create(GzipFileName)))
 83             {
 84                 zipoutputstream.SetLevel(CompressionLevel);
 85                 Crc32 crc = new Crc32();
 86                 Dictionary<string, DateTime> fileList = GetAllFies(dirPath);
 87                 foreach (KeyValuePair<string, DateTime> item in fileList)
 88                 {
 89                     FileStream fs = File.OpenRead(item.Key.ToString());
 90                     byte[] buffer = new byte[fs.Length];
 91                     fs.Read(buffer, 0, buffer.Length);
 92                     ZipEntry entry = new ZipEntry(item.Key.Substring(dirPath.Length));
 93                     entry.DateTime = item.Value;
 94                     entry.Size = fs.Length;
 95                     fs.Close();
 96                     crc.Reset();
 97                     crc.Update(buffer);
 98                     entry.Crc = crc.Value;
 99                     zipoutputstream.PutNextEntry(entry);
100                     zipoutputstream.Write(buffer, 0, buffer.Length);
101                 }
102             }
103             if (deleteDir)
104             {
105                 Directory.Delete(dirPath, true);
106             }
107         }
108         /// <summary>    
109         /// 獲取所有文件    
110         /// </summary>    
111         /// <returns></returns>    
112         private static Dictionary<string, DateTime> GetAllFies(string dir)
113         {
114             Dictionary<string, DateTime> FilesList = new Dictionary<string, DateTime>();
115             DirectoryInfo fileDire = new DirectoryInfo(dir);
116             if (!fileDire.Exists)
117             {
118                 throw new System.IO.FileNotFoundException("目錄:" + fileDire.FullName + "沒有找到!");
119             }
120             GetAllDirFiles(fileDire, FilesList);
121             GetAllDirsFiles(fileDire.GetDirectories(), FilesList);
122             return FilesList;
123         }
124         /// <summary>    
125         /// 獲取一個文件夾下的所有文件夾里的文件    
126         /// </summary>    
127         /// <param name="dirs"></param>    
128         /// <param name="filesList"></param>    
129         private static void GetAllDirsFiles(DirectoryInfo[] dirs, Dictionary<string, DateTime> filesList)
130         {
131             foreach (DirectoryInfo dir in dirs)
132             {
133                 foreach (FileInfo file in dir.GetFiles("*.*"))
134                 {
135                     filesList.Add(file.FullName, file.LastWriteTime);
136                 }
137                 GetAllDirsFiles(dir.GetDirectories(), filesList);
138             }
139         }
140         /// <summary>    
141         /// 獲取一個文件夾下的文件    
142         /// </summary>    
143         /// <param name="dir">目錄名稱</param>    
144         /// <param name="filesList">文件列表HastTable</param>    
145         private static void GetAllDirFiles(DirectoryInfo dir, Dictionary<string, DateTime> filesList)
146         {
147             foreach (FileInfo file in dir.GetFiles("*.*"))
148             {
149                 filesList.Add(file.FullName, file.LastWriteTime);
150             }
151         }
152         #endregion
153         #region 解壓縮文件
154         /// <summary>    
155         /// 解壓縮文件    
156         /// </summary>    
157         /// <param name="GzipFile">壓縮包文件名</param>    
158         /// <param name="targetPath">解壓縮目標路徑</param>           
159         public static void Decompress(string GzipFile, string targetPath)
160         {
161             //string directoryName = Path.GetDirectoryName(targetPath + "//") + "//";    
162             string directoryName = targetPath;
163             if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);//生成解壓目錄    
164             string CurrentDirectory = directoryName;
165             byte[] data = new byte[2048];
166             int size = 2048;
167             ZipEntry theEntry = null;
168             using (ZipInputStream s = new ZipInputStream(File.OpenRead(GzipFile)))
169             {
170                 while ((theEntry = s.GetNextEntry()) != null)
171                 {
172                     if (theEntry.IsDirectory)
173                     {// 該結點是目錄    
174                         if (!Directory.Exists(CurrentDirectory + theEntry.Name)) Directory.CreateDirectory(CurrentDirectory + theEntry.Name);
175                     }
176                     else
177                     {
178                         if (theEntry.Name != String.Empty)
179                         {
180                             //  檢查多級目錄是否存在  
181                             if (theEntry.Name.Contains("//"))
182                             {
183                                 string parentDirPath = theEntry.Name.Remove(theEntry.Name.LastIndexOf("//") + 1);
184                                 if (!Directory.Exists(parentDirPath))
185                                 {
186                                     Directory.CreateDirectory(CurrentDirectory + parentDirPath);
187                                 }
188                             }
189 
190                             //解壓文件到指定的目錄    
191                             using (FileStream streamWriter = File.Create(CurrentDirectory + theEntry.Name))
192                             {
193                                 while (true)
194                                 {
195                                     size = s.Read(data, 0, data.Length);
196                                     if (size <= 0) break;
197                                     streamWriter.Write(data, 0, size);
198                                 }
199                                 streamWriter.Close();
200                             }
201                         }
202                     }
203                 }
204                 s.Close();
205             }
206         }
207         #endregion
208     }
209 }
View Code

封裝的很徹底,基本不用修改什麼,直接拿來用就行了。

找了很久,終於知道怎麼把源代碼附上了

源代碼:https://files.cnblogs.com/files/hahahayang/C%E5%8E%8B%E7%BC%A9%E6%96%87%E4%BB%B6.zip


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

-Advertisement-
Play Games
更多相關文章
  • IDE進行Gradle操作,那麼還需要設置IDE的參數。例如在IDEA中,需要打開File->Other Settings->Default Settings->Gradle,在Gradle Vm Options中設置-Dfile.encoding=utf-8。這樣IDEA中的Gradle也可以正確 ...
  • GitHub RSA密碼 RSA密碼是1978年美國麻省理工學院三位密碼學者R.L.Rivest、A.Shamir和L.Adleman提出的一種基於大合數因數分解困難性的公開密鑰密碼。由於RSA密碼既可用於加密,又可用於數字簽名,通俗易懂,因此RSA密碼已成為目前應用最廣泛的公開密鑰密碼。 RSA加 ...
  • 首先需要安裝最新的python:安裝步驟見:https://www.cnblogs.com/weven/p/7252917.html 其次下載python源碼: 鏈接:https://pan.baidu.com/s/1UZmMEjt5nc7clMtatgLwzA 提取碼:qatx 然後就開始以下步驟 ...
  • 2019-01-19 多重背包:每種東西有多個,因此可以把它拆分成多個01背包 優化:二進位拆分(拆成1+2+4+8+16+...,分別表示2的n次冪) 比如18=1+2+4+8+3,可以證明18以內的任何數都可以用這幾個數的和或差表示(每個數只能用一次)(0時則背包為空), 所以就把2個,4個.. ...
  • 最近想要做一個小東西,用到了下麵幾個中間件或者環境: Java Tomcat Maven MongoDB ZooKeeper Node 並且恰好碰到騰訊雲打折,雲主機原價100多一個月,花了30塊錢買了三個月。買下後立即動手準備開始環境配置。 說到環境,少則2小時,多則兩三天可能都要整矇蔽,環境好了 ...
  • 寫之前的說明 0. 其實吧。 這個東西已經寫好了,地址在:https://github.com/hjx601496320/JdbcPlus 這 系列 文章算是我寫的過程的總結吧。(恩系列,說明我可能會寫好久,╮(╯▽╰)╭) 1. 現在有很多的現成的orm框架,為什麼還要自己寫一個? 框架這種東西個 ...
  • 開始研究動態代理之前 先簡要談下動態代理的概念 在不改變原有類結構的前提下增強類的功能以及對類原有方法操作,註意是方法不是屬性(屬性一般被設計為private修飾,不可以直接被調用) 動態代理的基本實例不做闡述,網上一大把 不理解的同學可以直接去搜索。 今天說的是自己在項目中遇到的一個實際的動態代理 ...
  • 引入 gRPC 是谷歌推出的一個高性能優秀的 RPC 框架,基於 HTTP/2 實現。並且該框架對 .NET Core 有著優秀的支持。最近在做一個項目正好用到了 gRPC,遇到了需要串流傳輸的問題。 引入 項目創建 首先還是需要安裝 .net core sdk,可以去 http://dot.net ...
一周排行
    -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.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...