项目中使用 Velocity 将模板和生成的动态内容(HTML、XML等)合并保存到redis数据库中,考虑到压缩的文件容量会比较小,方便传输而且存储所使用的空间也会比较小,所以要压缩一下,读取的时候也要解压,所以就用到了SharpZipLib。SharpZipLib是一个完全用c#为. net平台编写的Zip、GZip、Tar和BZip2库。官网代码下载https://github.com/icsharpcode/SharpZipLib。如果要使用SharpZipLib,我们可以直接下载源码引入项目,也可以下载SharpZLib.dll。SharpZLib.dll可以从网上下载也可以通过代码自己生成dill。

  压缩分为无损压缩和有损压缩,有损压缩指的是压缩之后就无法完整还原原始信息,但是压缩率可以很高,主要应用于视频、话音等数据的压缩,如果没必要完整还原信息,可以使用有损压缩,仅仅损失了一点信息,很难察觉;无损压缩则用于文件等等必须完整还原信息的场合,常见的无损压缩包括Zip、GZip、RAR、Tar、BZip2等。

一、如何使用SharpZipLib

  1、项目中引用SharpZLib.dll

  2、本项目中,单独写了一个ZipHelper类,用来使用SharpZipLib中封装的压缩方式。zipHelper类时可以作为使用Zip、Tar、GZip、Lzw、BZip2压缩方式的入口。直接上ZipHelper类的代码吧   

  1. using SharpZipLib.BZip2;
  2. using SharpZipLib.Checksum;
  3. using SharpZipLib.Core.Exceptions;
  4. using SharpZipLib.GZip;
  5. using SharpZipLib.Tar;
  6. using SharpZipLib.Zip;
  7. using SharpZipLib.Zip.Compression;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. using System.Text;
  12.  
  13. namespace SharpZipLibExample
  14. {
  15. /// <summary>
  16. /// 网上关于压缩的知识很多
  17. /// https://www.cnblogs.com/kissdodog/p/3525295.html
  18. /// </summary>
  19. public class ZipHelper
  20. {
  21. private const int BUFFER_LENGTH = ;
  22. #region Zip
  23. /// <summary>
  24. /// Zip文件压缩
  25. /// ZipOutputStream:相当于一个压缩包;
  26. /// ZipEntry:相当于压缩包里的一个文件;
  27. /// 以上两个类是SharpZipLib的主类。
  28. /// </summary>
  29. /// <param name="sourceFileLists"></param>
  30. /// <param name="descFile">压缩文件保存的目录</param>
  31. /// <param name="compression">压缩级别</param>
  32. public static void ZipCompress(List<string> sourceFileLists, string descFile, int compression)
  33. {
  34. if (compression < || compression > )
  35. {
  36. throw new ArgumentException("错误的压缩级别");
  37. }
  38. if (!Directory.Exists(new FileInfo(descFile).Directory.ToString()))
  39. {
  40. throw new ArgumentException("保存目录不存在");
  41. }
  42. foreach (string c in sourceFileLists)
  43. {
  44. if (!File.Exists(c))
  45. {
  46. throw new ArgumentException(string.Format("文件{0} 不存在!", c));
  47. }
  48. }
  49. Crc32 crc32 = new Crc32();
  50. using (ZipOutputStream stream = new ZipOutputStream(File.Create(descFile)))
  51. {
  52. stream.SetLevel(compression);
  53. ZipEntry entry;
  54. for (int i = ; i < sourceFileLists.Count; i++)
  55. {
  56. entry = new ZipEntry(Path.GetFileName(sourceFileLists[i]));
  57. entry.DateTime = DateTime.Now;
  58. using (FileStream fs = File.OpenRead(sourceFileLists[i]))
  59. {
  60. byte[] buffer = new byte[fs.Length];
  61. fs.Read(buffer, , buffer.Length);
  62. entry.Size = fs.Length;
  63. crc32.Reset();
  64. crc32.Update(buffer);
  65. entry.Crc = crc32.Value;
  66. stream.PutNextEntry(entry);
  67. stream.Write(buffer, , buffer.Length);
  68. }
  69. stream.CloseEntry();
  70. }
  71.  
  72. }
  73. }
  74. /// <summary>
  75. /// unZip文件解压缩
  76. /// </summary>
  77. /// <param name="sourceFile">要解压的文件</param>
  78. /// <param name="path">要解压到的目录</param>
  79. public static void ZipDeCompress(string sourceFile, string path)
  80. {
  81. if (!File.Exists(sourceFile))
  82. {
  83. throw new ArgumentException("要解压的文件不存在。");
  84. }
  85. if (!Directory.Exists(path))
  86. {
  87. throw new ArgumentException("要解压到的目录不存在!");
  88. }
  89. using (ZipInputStream s = new ZipInputStream(File.OpenRead(sourceFile)))
  90. {
  91. ZipEntry theEntry;
  92. while ((theEntry = s.GetNextEntry()) != null)
  93. {
  94. string fileName = System.IO.Path.GetFileName(theEntry.Name);
  95. if (fileName != string.Empty)
  96. {
  97. using (FileStream streamWriter = File.Create(path + @"\" + theEntry.Name))
  98. {
  99. int size = ;
  100. byte[] data = new byte[];
  101. while (true)
  102. {
  103. size = s.Read(data, , data.Length);
  104. if (size > )
  105. {
  106. streamWriter.Write(data, , size);
  107. }
  108. else
  109. {
  110. break;
  111. }
  112. }
  113. }
  114. }
  115. }
  116. }
  117. }
  118. /// <summary>
  119. /// 字符串压缩
  120. /// </summary>
  121. /// <param name="text">待压缩的字符串</param>
  122. /// <returns>已压缩的字符串</returns>
  123. public static string ZipCompress(string text)
  124. {
  125. string result = string.Empty;
  126. byte[] data = Encoding.UTF8.GetBytes(text);
  127. byte[] dData = ZipCompress(data);
  128. result = Convert.ToBase64String(dData);
  129. Array.Clear(dData, , dData.Length);
  130. return result;
  131. }
  132. /// <summary>
  133. /// 字符串解压
  134. /// </summary>
  135. /// <param name="text">待解压的字符串</param>
  136. /// <returns>已解压的字符串</returns>
  137. public static string ZipDeCompress(string text)
  138. {
  139. string result = string.Empty;
  140. byte[] data = Convert.FromBase64String(text);
  141. byte[] dData = ZipDeCompress(data);
  142. result = Encoding.UTF8.GetString(dData);
  143. Array.Clear(dData,,dData.Length);
  144. return result;
  145. }
  146. /// <summary>
  147. /// 字节数组压缩
  148. /// </summary>
  149. /// <param name="data">待压缩的字节数组</param>
  150. /// <param name="isClearData">压缩完成后,是否清除待压缩字节数组里面的内容</param>
  151. /// <returns>已压缩的字节数组</returns>
  152. public static byte[] ZipCompress(byte[] data, bool isClearData = true)
  153. {
  154. byte[] bytes = null;
  155. Deflater f = new Deflater(Deflater.BEST_COMPRESSION);
  156. f.SetInput(data);
  157. f.Finish();
  158. int count = ;
  159. using (MemoryStream o=new MemoryStream(data.Length))
  160. {
  161. byte[] buffer = new byte[BUFFER_LENGTH];
  162. while (!f.IsFinished)
  163. {
  164. count = f.Deflate(buffer);
  165. o.Write(buffer,,count);
  166. }
  167. bytes = o.ToArray();
  168. }
  169. if (isClearData)
  170. {
  171. Array.Clear(data,,data.Length);
  172. }
  173. return bytes;
  174. }
  175. /// <summary>
  176. /// 字节数组解压缩
  177. /// </summary>
  178. /// <param name="data">待解压缩的字节数组</param>
  179. /// <param name="isClearData">解压缩完成后,是否清除待解压缩字节数组里面的内容</param>
  180. /// <returns>已解压的字节数组</returns>
  181. public static byte[] ZipDeCompress(byte[] data, bool isClearData = true)
  182. {
  183. byte[] bytes = null;
  184. Inflater f = new Inflater();
  185. f.SetInput(data);
  186. int count = ;
  187. using (MemoryStream o=new MemoryStream(data.Length))
  188. {
  189. byte[] buffer = new byte[BUFFER_LENGTH];
  190. while (!f.IsFinished)
  191. {
  192. count = f.Inflate(buffer);
  193. o.Write(buffer,,count);
  194. }
  195. bytes = o.ToArray();
  196. }
  197. if (isClearData)
  198. {
  199. Array.Clear(data,,count);
  200. }
  201. return bytes;
  202. }
  203. #endregion
  204.  
  205. #region GZip
  206. /// <summary>
  207. /// 压缩字符串
  208. /// </summary>
  209. /// <param name="text">待压缩的字符串组</param>
  210. /// <returns>已压缩的字符串</returns>
  211. public static string GZipCompress(string text)
  212. {
  213. string result = string.Empty;
  214. byte[] data = Encoding.UTF8.GetBytes(text);
  215. byte[] cData = GZipCompress(data);
  216. result = Convert.ToBase64String(cData);
  217. Array.Clear(cData, , cData.Length);
  218. return result;
  219. }
  220. /// <summary>
  221. /// 解压缩字符串
  222. /// </summary>
  223. /// <param name="text">待解压缩的字符串</param>
  224. /// <returns>已解压缩的字符串</returns>
  225. public static string GZipDeCompress(string text)
  226. {
  227. string result = string.Empty;
  228. byte[] data = Convert.FromBase64String(text);
  229. byte[] cData = GZipDeCompress(data);
  230. result = Encoding.UTF8.GetString(cData);
  231. Array.Clear(cData, , cData.Length);
  232. return result;
  233. }
  234. /// <summary>
  235. /// 压缩字节数组
  236. /// </summary>
  237. /// <param name="data">待压缩的字节数组</param>
  238. /// <param name="isClearData">压缩完成后,是否清除待压缩字节数组里面的内容</param>
  239. /// <returns>已压缩的字节数组</returns>
  240. public static byte[] GZipCompress(byte[] data, bool isClearData = true)
  241. {
  242. byte[] bytes = null;
  243. try
  244. {
  245. using (MemoryStream o = new MemoryStream())
  246. {
  247. using (Stream s = new GZipOutputStream(o))
  248. {
  249. s.Write(data, , data.Length);
  250. s.Flush();
  251. }
  252. bytes = o.ToArray();
  253. }
  254. }
  255. catch (SharpZipBaseException)
  256. {
  257. }
  258. catch (IndexOutOfRangeException)
  259. {
  260. }
  261. if (isClearData)
  262. Array.Clear(data, , data.Length);
  263. return bytes;
  264. }
  265.  
  266. /// <summary>
  267. /// 解压缩字节数组
  268. /// </summary>
  269. /// <param name="data">待解压缩的字节数组</param>
  270. /// <param name="isClearData">解压缩完成后,是否清除待解压缩字节数组里面的内容</param>
  271. /// <returns>已解压的字节数组</returns>
  272. public static byte[] GZipDeCompress(byte[] data, bool isClearData = true)
  273. {
  274. byte[] bytes = null;
  275. try
  276. {
  277. using (MemoryStream o = new MemoryStream())
  278. {
  279. using (MemoryStream ms = new MemoryStream(data))
  280. {
  281. using (Stream s = new GZipInputStream(ms))
  282. {
  283. s.Flush();
  284. int size = ;
  285. byte[] buffer = new byte[BUFFER_LENGTH];
  286. while ((size = s.Read(buffer, , buffer.Length)) > )
  287. {
  288. o.Write(buffer, , size);
  289. }
  290. }
  291. }
  292. bytes = o.ToArray();
  293. }
  294. }
  295. catch (SharpZipBaseException)
  296. {
  297. }
  298. catch (IndexOutOfRangeException)
  299. {
  300. }
  301. if (isClearData)
  302. Array.Clear(data, , data.Length);
  303. return bytes;
  304. }
  305. #endregion
  306.  
  307. #region Tar
  308. /// <summary>
  309. /// 压缩字符串
  310. /// </summary>
  311. /// <param name="text">待压缩的字符串组</param>
  312. /// <returns>已压缩的字符串</returns>
  313. public static string TarCompress(string text)
  314. {
  315. string result = null;
  316. byte[] data = Encoding.UTF8.GetBytes(text);
  317. byte[] dData = TarCompress(data);
  318. result = Convert.ToBase64String(dData);
  319. Array.Clear(dData, , dData.Length);
  320. return result;
  321. }
  322. /// <summary>
  323. /// 解压缩字符串
  324. /// </summary>
  325. /// <param name="text">待解压缩的字符串</param>
  326. /// <returns>已解压的字符串</returns>
  327. public static string TarDeCompress(string text)
  328. {
  329. string result = null;
  330. byte[] data = Convert.FromBase64String(text);
  331. byte[] dData = TarDeCompress(data);
  332. result = Encoding.UTF8.GetString(dData);
  333. Array.Clear(dData, , dData.Length);
  334. return result;
  335. }
  336. /// <summary>
  337. /// 压缩字节数组
  338. /// </summary>
  339. /// <param name="data">待压缩的字节数组</param>
  340. /// <param name="isClearData">压缩完成后,是否清除待压缩字节数组里面的内容</param>
  341. /// <returns>已压缩的字节数组</returns>
  342. public static byte[] TarCompress(byte[] data, bool isClearData = true)
  343. {
  344. byte[] bytes = null;
  345. using (MemoryStream o = new MemoryStream())
  346. {
  347. using (Stream s = new TarOutputStream(o))
  348. {
  349. s.Write(data, , data.Length);
  350. s.Flush();
  351. }
  352. bytes = o.ToArray();
  353. }
  354. if (isClearData)
  355. Array.Clear(data, , data.Length);
  356. return bytes;
  357. }
  358. /// <summary>
  359. /// 解压缩字节数组
  360. /// </summary>
  361. /// <param name="data">待解压缩的字节数组</param>
  362. /// <param name="isClearData">解压缩完成后,是否清除待解压缩字节数组里面的内容</param>
  363. /// <returns>已解压的字节数组</returns>
  364. public static byte[] TarDeCompress(byte[] data, bool isClearData = true)
  365. {
  366. byte[] bytes = null;
  367. using (MemoryStream o = new MemoryStream())
  368. {
  369. using (MemoryStream ms = new MemoryStream(data))
  370. {
  371. using (Stream s = new TarInputStream(ms))
  372. {
  373. s.Flush();
  374. int size = ;
  375. byte[] buffer = new byte[BUFFER_LENGTH];
  376. while ((size = s.Read(buffer, , buffer.Length)) > )
  377. {
  378. o.Write(buffer, , size);
  379. }
  380. }
  381. }
  382. bytes = o.ToArray();
  383. }
  384. if (isClearData)
  385. Array.Clear(data, , data.Length);
  386. return bytes;
  387. }
  388. #endregion
  389.  
  390. #region BZip
  391. /// <summary>
  392. /// 压缩字符串
  393. /// </summary>
  394. /// <param name="text">待压缩的字符串组</param>
  395. /// <returns>已压缩的字符串</returns>
  396. public static string BZipCompress(string text)
  397. {
  398. string result = null;
  399. byte[] data = Encoding.UTF8.GetBytes(text);
  400. byte[] dData = BZipCompress(data);
  401. result = Convert.ToBase64String(dData);
  402. Array.Clear(dData, , dData.Length);
  403. return result;
  404. }
  405. /// <summary>
  406. /// 解压缩字符串
  407. /// </summary>
  408. /// <param name="text">待解压缩的字符串</param>
  409. /// <returns>已解压的字符串</returns>
  410. public static string BZipDeCompress(string text)
  411. {
  412. string result = null;
  413. byte[] data = Convert.FromBase64String(text);
  414. byte[] dData = BZipDeCompress(data);
  415. result = Encoding.UTF8.GetString(dData);
  416. Array.Clear(dData, , dData.Length);
  417. return result;
  418. }
  419. /// <summary>
  420. /// 压缩字节数组
  421. /// </summary>
  422. /// <param name="data">待压缩的字节数组</param>
  423. /// <param name="isClearData">压缩完成后,是否清除待压缩字节数组里面的内容</param>
  424. /// <returns>已压缩的字节数组</returns>
  425. public static byte[] BZipCompress(byte[] data, bool isClearData = true)
  426. {
  427. byte[] bytes = null;
  428. using (MemoryStream o = new MemoryStream())
  429. {
  430. using (Stream s = new BZip2OutputStream(o))
  431. {
  432. s.Write(data, , data.Length);
  433. s.Flush();
  434. }
  435. bytes = o.ToArray();
  436. }
  437. if (isClearData)
  438. Array.Clear(data, , data.Length);
  439. return bytes;
  440. }
  441. /// <summary>
  442. /// 解压缩字节数组
  443. /// </summary>
  444. /// <param name="data">待解压缩的字节数组</param>
  445. /// <param name="isClearData">解压缩完成后,是否清除待解压缩字节数组里面的内容</param>
  446. /// <returns>已解压的字节数组</returns>
  447. public static byte[] BZipDeCompress(byte[] data, bool isClearData = true)
  448. {
  449. byte[] bytes = null;
  450. using (MemoryStream o = new MemoryStream())
  451. {
  452. using (MemoryStream ms = new MemoryStream(data))
  453. {
  454. using (Stream s = new BZip2InputStream(ms))
  455. {
  456. s.Flush();
  457. int size = ;
  458. byte[] buffer = new byte[BUFFER_LENGTH];
  459. while ((size = s.Read(buffer, , buffer.Length)) > )
  460. {
  461. o.Write(buffer, , size);
  462. }
  463. }
  464. }
  465. bytes = o.ToArray();
  466. }
  467. if (isClearData)
  468. Array.Clear(data, , data.Length);
  469. return bytes;
  470. }
  471. #endregion
  472. }
  473. }

  3、程序入口main  

  1. using System;
  2. using System.Linq;
  3. using System.Text;
  4.  
  5. namespace SharpZipLibExample
  6. {
  7. class Program
  8. {
  9. static void Main(string[] args)
  10. {
  11. string strContent = "夜,结束了一天的喧嚣后安静下来,伴随着远处路灯那微弱的光。风,毫无预兆地席卷整片旷野,撩动人的思绪万千。星,遥遥地挂在天空之中,闪烁着它那微微星光,不如阳光般灿烂却如花儿般如痴如醉。";
  12. Console.WriteLine("原文:{0}",strContent);
  13. #region 压缩
  14. string compressContent = ZipHelper.BZipCompress(strContent);
  15. Console.WriteLine("压缩后的内容:{0};压缩后的内容大小:{1}", compressContent, Convert.FromBase64String(compressContent).Count().ToString());
  16. #endregion
  17.  
  18. #region 解压缩
  19. strContent = ZipHelper.BZipDeCompress(compressContent);
  20. Console.WriteLine("解压缩后的内容:{0};解压缩后的内容大小:{1}", strContent,Encoding.UTF8.GetBytes(strContent).Count().ToString());
  21. #endregion
  22. Console.ReadKey();
  23. }
  24. }
  25. }  

SharpZipLib的详细解析详见 https://www.cnblogs.com/kissdodog/p/3525295.html

完整的Demo下载地址https://download.csdn.net/download/u011392711/10827889

C#基础知识之SharpZipLib压缩解压的使用的更多相关文章

  1. .NET使用ICSharpCode.SharpZipLib压缩/解压文件

    SharpZipLib是国外开源加压解压库,可以方便的对文件进行加压/解压 1.下载ICSharpCode.SharpZipLib.dll,并复制到bin目录下 http://www.icsharpc ...

  2. SharpZipLib压缩解压

    一.介绍 SharpZipLib是一个完全由C#编写的ZIP,GZIP,Tar和BZIP2 Library,可以方便的支持这几种格式的压缩和解压缩. https://github.com/icshar ...

  3. ICSharpCode.SharpZipLib压缩解压

    一.使用ICSharpCode.SharpZipLib.dll: 下载地址 http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.asp ...

  4. SharpZipLib压缩解压的使用

    项目中使用 Velocity 将模板和生成的动态内容(HTML.XML等)合并保存到redis数据库中,考虑到压缩的文件容量会比较小,方便传输而且存储所使用的空间也会比较小,所以要压缩一下,读取的时候 ...

  5. C#使用SharpZipLib压缩解压文件

    #region 加压解压方法 /// <summary> /// 功能:压缩文件(暂时只压缩文件夹下一级目录中的文件,文件夹及其子级被忽略) /// </summary> // ...

  6. 通过SharpZipLib来压缩解压文件

    在项目开发中,一些比较常用的功能就是压缩解压文件了,其实类似的方法有许多 ,现将通过第三方类库SharpZipLib来压缩解压文件的方法介绍如下,主要目的是方便以后自己阅读,当然可以帮到有需要的朋友更 ...

  7. 使用SharpZIpLib写的压缩解压操作类

    使用SharpZIpLib写的压缩解压操作类,已测试. public class ZipHelper { /// <summary> /// 压缩文件 /// </summary&g ...

  8. huffman压缩解压文件【代码】

    距离上次写完哈夫曼编码已经过去一周了,这一周都在写huffman压缩解压,哎,在很多小错误上浪费了很多时间调bug.其实这个程序的最关键部分不是我自己想的,而是借鉴了某位园友的代码,但是,无论如何,自 ...

  9. (转载)C#压缩解压zip 文件

    转载之: C#压缩解压zip 文件 - 大气象 - 博客园http://www.cnblogs.com/greatverve/archive/2011/12/27/csharp-zip.html C# ...

随机推荐

  1. Spring的Aop理解

    主要作用:解决代码复用,避免重复性编写代码. 比较典型的场景:日志打印,权限验证,事务处理 参考网址为:http://moon-walker.iteye.com/blog/2381532 spring ...

  2. linux命令--truncate 学习

    truncate命令可以将一个文件缩小或者扩展到某个给定的大小 可以利用该命令和-s选项来特别指定文件的大小 1.清空一个文件内容,尤其是log 2. truncate -s 0 test

  3. JVM监控工具之jmap、jstat、stack、jps、jstatd、jinfo、jhat、jdb

    1.jdb(The Java Debuger) jdb 用来对core文件和正在运行的Java进程进行实时地调试,里面包含了丰富的命令帮助您进行调试,它的功能和Sun studio里面所带的dbx非常 ...

  4. 【Qt开发】解决Qt5.7.0中文显示乱码的问题

    [Qt开发]解决Qt5.7.0中文显示乱码的问题 亲测可用: 乱码主要是编码格式的问题,这里可以通过Edit菜单中选择当前文档的编码方式,选择按照UTF-8格式保存,然后输入对应的中文,保存,然后运行 ...

  5. Windows.命令行(CMD)_执行命令&环境变量

    1.CMD命令中如果 命令有换行的话,就使用 ^来连接(这就类似于 Linux命令行中 \ 的作用) 2.环境变量 2.1.显示 所有环境变量的值,命令:set 2.2.显示 某个环境变量的值,命令 ...

  6. Java中类和接口

    很形象的接口的使用——针对初学者 里氏代换原则是什么?听起来很高深,不过我们也不是什么学院派,就不讲大道理了,直接拿个例子来说一下. 我们拿人和程序员举个例子.人是一个大类,程序员是继承自人的子类.看 ...

  7. if——while表达式详解

    ①while循环的表达式是循环进行的条件,用作循环条件的表达式中一般至少包括一个能够改变表达式的变量,这个变量称为循环变量 ②当表达式的值为真(非零)(非空)时,执行循环体:为假(0)时,则循环结束 ...

  8. Linux系统常用命令之top

    top - 06:58:37 up 7 days, 23:36, 2 users, load average: 0.00, 0.01, 0.05Tasks: 716 total, 1 running, ...

  9. js swich

    <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...

  10. 期货、股指期权、ETF期权

    期货与期权: 期权是指一种合约,该合约赋予持有人在某一特定日期或该日之前的任何时间以固定价格购进或售出某种资产的权利. 期货是标准化的合约,赋予参与者在未来的某个时间点以约定好的一个价格去买入或者卖出 ...