热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

C#ICSharpCode.SharpZipLib压缩、解压文件附源码

http:www.icsharpcode.netopensourcesharpziplib有SharpZiplib的最新版本,本文使用的版本为0.86.0.518,支持Zip,GZ

http://www.icsharpcode.net/opensource/sharpziplib/ 有SharpZiplib的最新版本,本文使用的版本为0.86.0.518,支持Zip, GZip, BZip2 和Tar格式。我们需要dll 在官网上也有。

好了,深入的大家还要多多研究,今天我们简单介绍一下 简单的 单文件、文件夹的压缩和解压

 

先给大家看一下效果:

 

 

一、引入ICSharpCode.SharpZipLib

我们新建个帮助类 ZipHelper.cs  然后 添加 dll 引用 

 

 

二、添加完dll引用之后 我们 需要添加 这几个Using引用
 
  1. 1 using ICSharpCode.SharpZipLib.Checksums;

  2. 2 using ICSharpCode.SharpZipLib.Zip;

  3. 3 using System;4 using System.IO;

 

 

 

三、压缩单个文件

这里我添加了几个参数 大家可以根据自己的需要 修改一下 

 
  1. 1 ///

  2. 2 /// ZIP:压缩单个文件

  3. 3 /// add yuangang by 2016-06-13

  4. 4 ///

  5. 5 /// 需要压缩的文件(绝对路径)

  6. 6 /// 压缩后的文件路径(绝对路径)

  7. 7 /// 压缩后的文件名称(文件名,默认 同源文件同名)

  8. 8 /// 压缩等级(0 无 - 9 最高,默认 5)

  9. 9 /// 缓存大小(每次写入文件大小,默认 2048)

  10. 10 /// 是否加密(默认 加密)

  11. 11 public static void ZipFile(string FileToZip, string ZipedPath, string ZipedFileName = "", int CompressiOnLevel= 5, int BlockSize = 2048, bool IsEncrypt = true)

  12. 12 {

  13. 13 //如果文件没有找到,则报错

  14. 14 if (!System.IO.File.Exists(FileToZip))

  15. 15 {

  16. 16 throw new System.IO.FileNotFoundException("指定要压缩的文件: " + FileToZip + " 不存在!");

  17. 17 }

  18. 18

  19. 19 //文件名称(默认同源文件名称相同)

  20. 20 string ZipFileName = string.IsNullOrEmpty(ZipedFileName) ? ZipedPath + "\" + new FileInfo(FileToZip).Name.Substring(0, new FileInfo(FileToZip).Name.LastIndexOf(".")) + ".zip" : ZipedPath + "\" + ZipedFileName + ".zip";

  21. 21

  22. 22 using (System.IO.FileStream ZipFile = System.IO.File.Create(ZipFileName))

  23. 23 {

  24. 24 using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile))

  25. 25 {

  26. 26 using (System.IO.FileStream StreamToZip = new System.IO.FileStream(FileToZip, System.IO.FileMode.Open, System.IO.FileAccess.Read))

  27. 27 {

  28. 28 string fileName = FileToZip.Substring(FileToZip.LastIndexOf("\") + 1);

  29. 29

  30. 30 ZipEntry ZipEntry = new ZipEntry(fileName);

  31. 31

  32. 32 if (IsEncrypt)

  33. 33 {

  34. 34 //压缩文件加密

  35. 35 ZipStream.Password = “123”;

  36. 36 }

  37. 37

  38. 38 ZipStream.PutNextEntry(ZipEntry);

  39. 39

  40. 40 //设置压缩级别

  41. 41 ZipStream.SetLevel(CompressionLevel);

  42. 42

  43. 43 //缓存大小

  44. 44 byte[] buffer = new byte[BlockSize];

  45. 45

  46. 46 int sizeRead = 0;

  47. 47

  48. 48 try

  49. 49 {

  50. 50 do

  51. 51 {

  52. 52 sizeRead = StreamToZip.Read(buffer, 0, buffer.Length);

  53. 53 ZipStream.Write(buffer, 0, sizeRead);

  54. 54 }

  55. 55 while (sizeRead > 0);

  56. 56 }

  57. 57 catch (System.Exception ex)

  58. 58 {

  59. 59 throw ex;

  60. 60 }

  61. 61

  62. 62 StreamToZip.Close();

  63. 63 }

  64. 64

  65. 65 ZipStream.Finish();

  66. 66 ZipStream.Close();

  67. 67 }

  68. 68

  69. 69 ZipFile.Close();

  70. 70 }

  71. 71 }

 

 

 

四、压缩文件夹
 
  1. 1 ///

  2. 2 /// ZIP:压缩文件夹

  3. 3 /// add yuangang by 2016-06-13

  4. 4 ///

  5. 5 /// 需要压缩的文件夹(绝对路径)

  6. 6 /// 压缩后的文件路径(绝对路径)

  7. 7 /// 压缩后的文件名称(文件名,默认 同源文件夹同名)

  8. 8 /// 是否加密(默认 加密)

  9. 9 public static void ZipDirectory(string DirectoryToZip, string ZipedPath, string ZipedFileName = "", bool IsEncrypt = true)

  10. 10 {

  11. 11 //如果目录不存在,则报错

  12. 12 if (!System.IO.Directory.Exists(DirectoryToZip))

  13. 13 {

  14. 14 throw new System.IO.FileNotFoundException("指定的目录: " + DirectoryToZip + " 不存在!");

  15. 15 }

  16. 16

  17. 17 //文件名称(默认同源文件名称相同)

  18. 18 string ZipFileName = string.IsNullOrEmpty(ZipedFileName) ? ZipedPath + "\" + new DirectoryInfo(DirectoryToZip).Name + ".zip" : ZipedPath + "\" + ZipedFileName + ".zip";

  19. 19

  20. 20 using (System.IO.FileStream ZipFile = System.IO.File.Create(ZipFileName))

  21. 21 {

  22. 22 using (ZipOutputStream s = new ZipOutputStream(ZipFile))

  23. 23 {

  24. 24 if (IsEncrypt)

  25. 25 {

  26. 26 //压缩文件加密

  27. 27 s.Password = “123”;

  28. 28 }

  29. 29 ZipSetp(DirectoryToZip, s, "");

  30. 30 }

  31. 31 }

  32. 32 }

  33. 33 ///

  34. 34 /// 递归遍历目录

  35. 35 /// add yuangang by 2016-06-13

  36. 36 ///

  37. 37 private static void ZipSetp(string strDirectory, ZipOutputStream s, string parentPath)

  38. 38 {

  39. 39 if (strDirectory[strDirectory.Length - 1] != Path.DirectorySeparatorChar)

  40. 40 {

  41. 41 strDirectory += Path.DirectorySeparatorChar;

  42. 42 }

  43. 43 Crc32 crc = new Crc32();

  44. 44

  45. 45 string[] filenames = Directory.GetFileSystemEntries(strDirectory);

  46. 46

  47. 47 foreach (string file in filenames)// 遍历所有的文件和目录

  48. 48 {

  49. 49

  50. 50 if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件

  51. 51 {

  52. 52 string pPath = parentPath;

  53. 53 pPath += file.Substring(file.LastIndexOf("\") + 1);

  54. 54 pPath += "\";

  55. 55 ZipSetp(file, s, pPath);

  56. 56 }

  57. 57

  58. 58 else // 否则直接压缩文件

  59. 59 {

  60. 60 //打开压缩文件

  61. 61 using (FileStream fs = File.OpenRead(file))

  62. 62 {

  63. 63

  64. 64 byte[] buffer = new byte[fs.Length];

  65. 65 fs.Read(buffer, 0, buffer.Length);

  66. 66

  67. 67 string fileName = parentPath + file.Substring(file.LastIndexOf("\") + 1);

  68. 68 ZipEntry entry = new ZipEntry(fileName);

  69. 69

  70. 70 entry.DateTime = DateTime.Now;

  71. 71 entry.Size = fs.Length;

  72. 72

  73. 73 fs.Close();

  74. 74

  75. 75 crc.Reset();

  76. 76 crc.Update(buffer);

  77. 77

  78. 78 entry.Crc = crc.Value;

  79. 79 s.PutNextEntry(entry);

  80. 80

  81. 81 s.Write(buffer, 0, buffer.Length);

  82. 82 }

  83. 83 }

  84. 84 }

  85. 85 }

 

 

 

五、解压一个ZIP文件
 
  1. 1 ///

  2. 2 /// ZIP:解压一个zip文件

  3. 3 /// add yuangang by 2016-06-13

  4. 4 ///

  5. 5 /// 需要解压的Zip文件(绝对路径)

  6. 6 /// 解压到的目录

  7. 7 /// 解压密码

  8. 8 /// 是否覆盖已存在的文件

  9. 9 public static void UnZip(string ZipFile, string TargetDirectory, string Password, bool OverWrite = true)

  10. 10 {

  11. 11 //如果解压到的目录不存在,则报错

  12. 12 if (!System.IO.Directory.Exists(TargetDirectory))

  13. 13 {

  14. 14 throw new System.IO.FileNotFoundException("指定的目录: " + TargetDirectory + " 不存在!");

  15. 15 }

  16. 16 //目录结尾

  17. 17 if (!TargetDirectory.EndsWith("\")) { TargetDirectory = TargetDirectory + "\"; }

  18. 18

  19. 19 using (ZipInputStream zipfiles = new ZipInputStream(File.OpenRead(ZipFile)))

  20. 20 {

  21. 21 zipfiles.Password = Password;

  22. 22 ZipEntry theEntry;

  23. 23

  24. 24 while ((theEntry = zipfiles.GetNextEntry()) != null)

  25. 25 {

  26. 26 string directoryName = "";

  27. 27 string pathToZip = "";

  28. 28 pathToZip = theEntry.Name;

  29. 29

  30. 30 if (pathToZip != "")

  31. 31 directoryName = Path.GetDirectoryName(pathToZip) + "\";

  32. 32

  33. 33 string fileName = Path.GetFileName(pathToZip);

  34. 34

  35. 35 Directory.CreateDirectory(TargetDirectory + directoryName);

  36. 36

  37. 37 if (fileName != "")

  38. 38 {

  39. 39 if ((File.Exists(TargetDirectory + directoryName + fileName) && OverWrite) || (!File.Exists(TargetDirectory + directoryName + fileName)))

  40. 40 {

  41. 41 using (FileStream streamWriter = File.Create(TargetDirectory + directoryName + fileName))

  42. 42 {

  43. 43 int size = 2048;

  44. 44 byte[] data = new byte[2048];

  45. 45 while (true)

  46. 46 {

  47. 47 size = zipfiles.Read(data, 0, data.Length);

  48. 48

  49. 49 if (size > 0)

  50. 50 streamWriter.Write(data, 0, size);

  51. 51 else

  52. 52 break;

  53. 53 }

  54. 54 streamWriter.Close();

  55. 55 }

  56. 56 }

  57. 57 }

  58. 58 }

  59. 59

  60. 60 zipfiles.Close();

  61. 61 }

  62. 62 }

 

 

 

转载至 http://www.cnblogs.com/yuangang/p/5581391.html

非原创文章, 转载请尊重作者劳动成果 http://yuangang.cnblogs.com


推荐阅读
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
  • 本文分享了一个关于在C#中使用异步代码的问题,作者在控制台中运行时代码正常工作,但在Windows窗体中却无法正常工作。作者尝试搜索局域网上的主机,但在窗体中计数器没有减少。文章提供了相关的代码和解决思路。 ... [详细]
  • [大整数乘法] java代码实现
    本文介绍了使用java代码实现大整数乘法的过程,同时也涉及到大整数加法和大整数减法的计算方法。通过分治算法来提高计算效率,并对算法的时间复杂度进行了研究。详细代码实现请参考文章链接。 ... [详细]
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • 本文介绍了C#中生成随机数的三种方法,并分析了其中存在的问题。首先介绍了使用Random类生成随机数的默认方法,但在高并发情况下可能会出现重复的情况。接着通过循环生成了一系列随机数,进一步突显了这个问题。文章指出,随机数生成在任何编程语言中都是必备的功能,但Random类生成的随机数并不可靠。最后,提出了需要寻找其他可靠的随机数生成方法的建议。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • C# 7.0 新特性:基于Tuple的“多”返回值方法
    本文介绍了C# 7.0中基于Tuple的“多”返回值方法的使用。通过对C# 6.0及更早版本的做法进行回顾,提出了问题:如何使一个方法可返回多个返回值。然后详细介绍了C# 7.0中使用Tuple的写法,并给出了示例代码。最后,总结了该新特性的优点。 ... [详细]
  • 本文介绍了一个在线急等问题解决方法,即如何统计数据库中某个字段下的所有数据,并将结果显示在文本框里。作者提到了自己是一个菜鸟,希望能够得到帮助。作者使用的是ACCESS数据库,并且给出了一个例子,希望得到的结果是560。作者还提到自己已经尝试了使用"select sum(字段2) from 表名"的语句,得到的结果是650,但不知道如何得到560。希望能够得到解决方案。 ... [详细]
  • 本文介绍了南邮ctf-web的writeup,包括签到题和md5 collision。在CTF比赛和渗透测试中,可以通过查看源代码、代码注释、页面隐藏元素、超链接和HTTP响应头部来寻找flag或提示信息。利用PHP弱类型,可以发现md5('QNKCDZO')='0e830400451993494058024219903391'和md5('240610708')='0e462097431906509019562988736854'。 ... [详细]
  • This article discusses the efficiency of using char str[] and char *str and whether there is any reason to prefer one over the other. It explains the difference between the two and provides an example to illustrate their usage. ... [详细]
  • 基于Socket的多个客户端之间的聊天功能实现方法
    本文介绍了基于Socket的多个客户端之间实现聊天功能的方法,包括服务器端的实现和客户端的实现。服务器端通过每个用户的输出流向特定用户发送消息,而客户端通过输入流接收消息。同时,还介绍了相关的实体类和Socket的基本概念。 ... [详细]
  • GreenDAO快速入门
    前言之前在自己做项目的时候,用到了GreenDAO数据库,其实对于数据库辅助工具库从OrmLite,到litePal再到GreenDAO,总是在不停的切换,但是没有真正去了解他们的 ... [详细]
  • 本文整理了Java面试中常见的问题及相关概念的解析,包括HashMap中为什么重写equals还要重写hashcode、map的分类和常见情况、final关键字的用法、Synchronized和lock的区别、volatile的介绍、Syncronized锁的作用、构造函数和构造函数重载的概念、方法覆盖和方法重载的区别、反射获取和设置对象私有字段的值的方法、通过反射创建对象的方式以及内部类的详解。 ... [详细]
  • 本文详细介绍了使用C#实现Word模版打印的方案。包括添加COM引用、新建Word操作类、开启Word进程、加载模版文件等步骤。通过该方案可以实现C#对Word文档的打印功能。 ... [详细]
  • C#多线程解决界面卡死问题的完美解决方案
    当界面需要在程序运行中不断更新数据时,使用多线程可以解决界面卡死的问题。一个主线程创建界面,使用一个子线程执行程序并更新主界面,可以避免卡死现象。本文分享了一个例子,供大家参考。 ... [详细]
author-avatar
手机用户2602897795
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有