C# 文件/文件夹压缩解压缩

 

项目上用到的,随手做个记录,哈哈。

直接上代码:

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

封装的很彻底,基本不用修改什么,直接拿来用就行了。

找了很久,终于知道怎么把源代码附上了

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

c#压缩和解压缩的更多相关文章

  1. Linux下的压缩和解压缩命令——gzip/gunzip

    gzip命令 gzip命令用来压缩文件.gzip是个使用广泛的压缩程序,文件经它压缩过后,其名称后面会多处".gz"扩展名. gzip是在Linux系统中经常使用的一个对文件进行压 ...

  2. Linux常用命令学习3---(文件的压缩和解压缩命令zip unzip tar、关机和重启命令shutdown reboot……)

    1.压缩和解压缩命令    常用压缩格式:.zip..gz..bz2..tar.gz..tar.bz2..rar .zip格式压缩和解压缩命令        zip 压缩文件名 源文件:压缩文件   ...

  3. [Java 基础] 使用java.util.zip包压缩和解压缩文件

    reference :  http://www.open-open.com/lib/view/open1381641653833.html Java API中的import java.util.zip ...

  4. 关于webservice大数据量传输时的压缩和解压缩

    当访问WebSerivice时,如果数据量很大,传输数据时就会很慢.为了提高速度,我们就会想到对数据进行压缩.首先我们来分析一下. 当在webserice中传输数据时,一般都采用Dataset进行数据 ...

  5. 重新想象 Windows 8 Store Apps (70) - 其它: 文件压缩和解压缩, 与 Windows 商店相关的操作, app 与 web, 几个 Core 的应用, 页面的生命周期和程序的生命周期

    [源码下载] 重新想象 Windows 8 Store Apps (70) - 其它: 文件压缩和解压缩, 与 Windows 商店相关的操作, app 与 web, 几个 Core 的应用, 页面的 ...

  6. IOS开发之网络编程--文件压缩和解压缩

    前言: QQ表情包就用到了解压缩,从网络下载的那么多表情文件格式并不是一个一个图片文件,而是多个图片压缩而成的表情压缩包.下面介绍的是iOS开发中会用到的压缩和解压缩的第三方框架的使用. 注意: 这个 ...

  7. 压缩和解压缩gz包

    gz是Linux和OSX中常见的压缩文件格式,下面是用java压缩和解压缩gz包的例子 public class GZIPcompress { public static void FileCompr ...

  8. 在C#中利用SharpZipLib进行文件的压缩和解压缩收藏

    我在做项目的时候需要将文件进行压缩和解压缩,于是就从http://www.icsharpcode.net(http://www.icsharpcode.net/OpenSource/SharpZipL ...

  9. C#- 压缩和解压缩的研究 .

    用了第二种方法,感觉很不错,其他都没用过了.摘录下来,做一个备忘. 最近在网上查了一下在.net中进行压缩和解压缩的方法,方法有很多,我找到了以下几种: 1.利用.net自带的压缩和解压缩方法GZip ...

  10. .net中压缩和解压缩的处理

    最近在网上查了一下在.net中进行压缩和解压缩的方法,方法有很多,我找到了以下几种: 1.利用.net自带的压缩和解压缩方法GZip 参考代码如下: //======================= ...

随机推荐

  1. 《ucore lab1 exercise6》实验报告

    资源 ucore在线实验指导书 我的ucore实验代码 题目:完善中断初始化和处理 请完成编码工作和回答如下问题: 中断描述符表(也可简称为保护模式下的中断向量表)中一个表项占多少字节?其中哪几位代表 ...

  2. 024 Android 自定义样式对话框(AlertDialog)

    1.AlertDialog介绍 AlertDialog并不需要到布局文件中创建,而是在代码中通过构造器(AlertDialog.Builder)来构造标题.图标和按钮等内容的. 常规使用步骤(具体参见 ...

  3. git config 介绍

    转载. https://blog.csdn.net/liuxiao723846/article/details/83113317 Git的三个重要配置文件分别是/etc/gitconfig,${HOM ...

  4. 开始使用 Ubuntu(字体渲染去模糊+软件安装+优化配置+常见错误)(29)

    1. 中文字体渲染美化 + 去模糊 步骤: 1. 解压安装 lulinux_fontsConf_181226.tar.gz,按里面的安装说明操作: 2. 开启字体渲染: 打开 unity-tweak- ...

  5. Windows10下Anaconda+Tensorflow+Keras环境配置

    注意!注意!!注意!!! (重要的事情说三遍) 安装前检查: 1.Tensorflow不支持Anaconda2,Tensorflow也不支持python2.7和python3.7(满满的辛酸泪!) 2 ...

  6. Python18之函数定义及调用,注释

    一.函数定义 def 函数名(形参1,形参2...): 函数体 return 返回值         (可以返回任何东西,一个值,一个变量,或是另一个函数的返回值,如果函数没有返回值,可以省略retu ...

  7. python学习-57 logging模块

    logging 1.basicConfig方式 import logging # 以下是日志的级别 logging.debug('debug message') logging.info('info ...

  8. 信息的Raid存储方式,更安全的保障,更花钱的保障!

    raid0 就是把多个(最少2个)硬盘合并成1个逻辑盘使用,数据读写时对各硬盘同时操作,不同硬盘写入不同数据,速度快. raid1就是同时对2个硬盘读写(同样的数据).强调数据的安全性.比较浪费. r ...

  9. java使用poi操作word, 支持动态的行(一个占位符插入多条)和表格中动态行, 支持图片

    依赖 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifa ...

  10. Vue组件全局/局部注册

    全局注册 main.js中创建 Vue.component('button-counter', { data: function () { return { count: 0 } }, templat ...