服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C# 使用SharpZipLib生成压缩包的实例代码

C# 使用SharpZipLib生成压缩包的实例代码

2022-03-01 14:29Alan.hsiang C#

SharpZipLib是一个C#的类库,主要用来解压缩Zip,GZip,BZip2,Tar等格式,是以托管程序集的方式实现,可以方便的应用于其他的项目之中。本文通过一个实例代码给大家介绍了C# 使用SharpZipLib生成压缩包的方法,感兴趣的朋友跟随小编一起

本文通过一个简单的小例子简述sharpziplib压缩文件的常规用法,仅供学习分享使用,如有不足之处,还请指正。

什么是sharpziplib ?

sharpziplib是一个c#的类库,主要用来解压缩zip,gzip,bzip2,tar等格式,是以托管程序集的方式实现,可以方便的应用于其他的项目之中。

在工程中引用sharpziplib

在项目中,点击项目名称右键-->管理nuget程序包,打开nuget包管理器窗口,进行搜索下载即可,如下图所示:

C# 使用SharpZipLib生成压缩包的实例代码

sharpziplib的关键类结构图

如下所示:

C# 使用SharpZipLib生成压缩包的实例代码

涉及知识点:

•zipoutputstream 压缩输出流,将文件一个接一个的写入压缩文档,此类不是线程安全的。
•putnextentry 开始一个新的zip条目,zipoutputstream中的方法。
•zipentry 一个zip文件中的条目,可以理解为压缩包里面的一个文件夹/文件。
•zipinputstream 解压缩输出流,从压缩包中一个接一个的读出文档。
•getnextentry 读出zip条目,zipinputstream中的方法。

示例效果图:

关于解压缩小例子的示例效果图,如下:

C# 使用SharpZipLib生成压缩包的实例代码

核心代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
using icsharpcode.sharpziplib.checksum;
using icsharpcode.sharpziplib.zip;
using system;
using system.collections.generic;
using system.io;
using system.linq;
using system.text;
using system.threading.tasks;
namespace demozip
{
  class ziphelper
  {
    private string rootpath = string.empty;
    #region 压缩
    /// <summary> 
    /// 递归压缩文件夹的内部方法 
    /// </summary> 
    /// <param name="foldertozip">要压缩的文件夹路径</param> 
    /// <param name="zipstream">压缩输出流</param> 
    /// <param name="parentfoldername">此文件夹的上级文件夹</param> 
    /// <returns></returns> 
    private bool zipdirectory(string foldertozip, zipoutputstream zipstream, string parentfoldername)
    {
      bool result = true;
      string[] folders, files;
      zipentry ent = null;
      filestream fs = null;
      crc32 crc = new crc32();
      try
      {
        string entname = foldertozip.replace(this.rootpath, string.empty)+"/";
        //path.combine(parentfoldername, path.getfilename(foldertozip) + "/")
        ent = new zipentry(entname);
        zipstream.putnextentry(ent);
        zipstream.flush();
        files = directory.getfiles(foldertozip);
        foreach (string file in files)
        {
          fs = file.openread(file);
          byte[] buffer = new byte[fs.length];
          fs.read(buffer, 0, buffer.length);
          ent = new zipentry(entname + path.getfilename(file));
          ent.datetime = datetime.now;
          ent.size = fs.length;
          fs.close();
          crc.reset();
          crc.update(buffer);
          ent.crc = crc.value;
          zipstream.putnextentry(ent);
          zipstream.write(buffer, 0, buffer.length);
        }
      }
      catch
      {
        result = false;
      }
      finally
      {
        if (fs != null)
        {
          fs.close();
          fs.dispose();
        }
        if (ent != null)
        {
          ent = null;
        }
        gc.collect();
        gc.collect(1);
      }
      folders = directory.getdirectories(foldertozip);
      foreach (string folder in folders)
        if (!zipdirectory(folder, zipstream, foldertozip))
          return false;
      return result;
    }
    /// <summary> 
    /// 压缩文件夹 
    /// </summary> 
    /// <param name="foldertozip">要压缩的文件夹路径</param> 
    /// <param name="zipedfile">压缩文件完整路径</param> 
    /// <param name="password">密码</param> 
    /// <returns>是否压缩成功</returns> 
    public bool zipdirectory(string foldertozip, string zipedfile, string password)
    {
      bool result = false;
      if (!directory.exists(foldertozip))
        return result;
      zipoutputstream zipstream = new zipoutputstream(file.create(zipedfile));
      zipstream.setlevel(6);
      if (!string.isnullorempty(password)) zipstream.password = password;
      result = zipdirectory(foldertozip, zipstream, "");
      zipstream.finish();
      zipstream.close();
      return result;
    }
    /// <summary> 
    /// 压缩文件夹 
    /// </summary> 
    /// <param name="foldertozip">要压缩的文件夹路径</param> 
    /// <param name="zipedfile">压缩文件完整路径</param> 
    /// <returns>是否压缩成功</returns> 
    public bool zipdirectory(string foldertozip, string zipedfile)
    {
      bool result = zipdirectory(foldertozip, zipedfile, null);
      return result;
    }
    /// <summary> 
    /// 压缩文件 
    /// </summary> 
    /// <param name="filetozip">要压缩的文件全名</param> 
    /// <param name="zipedfile">压缩后的文件名</param> 
    /// <param name="password">密码</param> 
    /// <returns>压缩结果</returns> 
    public bool zipfile(string filetozip, string zipedfile, string password)
    {
      bool result = true;
      zipoutputstream zipstream = null;
      filestream fs = null;
      zipentry ent = null;
      if (!file.exists(filetozip))
        return false;
      try
      {
        fs = file.openread(filetozip);
        byte[] buffer = new byte[fs.length];
        fs.read(buffer, 0, buffer.length);
        fs.close();
        fs = file.create(zipedfile);
        zipstream = new zipoutputstream(fs);
        if (!string.isnullorempty(password)) zipstream.password = password;
        ent = new zipentry(path.getfilename(filetozip));
        zipstream.putnextentry(ent);
        zipstream.setlevel(6);
        zipstream.write(buffer, 0, buffer.length);
      }
      catch
      {
        result = false;
      }
      finally
      {
        if (zipstream != null)
        {
          zipstream.finish();
          zipstream.close();
        }
        if (ent != null)
        {
          ent = null;
        }
        if (fs != null)
        {
          fs.close();
          fs.dispose();
        }
      }
      gc.collect();
      gc.collect(1);
      return result;
    }
    /// <summary> 
    /// 压缩文件 
    /// </summary> 
    /// <param name="filetozip">要压缩的文件全名</param> 
    /// <param name="zipedfile">压缩后的文件名</param> 
    /// <returns>压缩结果</returns> 
    public bool zipfile(string filetozip, string zipedfile)
    {
      bool result = zipfile(filetozip, zipedfile, null);
      return result;
    }
    /// <summary> 
    /// 压缩文件或文件夹 
    /// </summary> 
    /// <param name="filetozip">要压缩的路径</param> 
    /// <param name="zipedfile">压缩后的文件名</param> 
    /// <param name="password">密码</param> 
    /// <returns>压缩结果</returns> 
    public bool zip(string filetozip, string zipedfile, string password)
    {
      bool result = false;
      if (directory.exists(filetozip))
      {
        this.rootpath = path.getdirectoryname(filetozip);
        result = zipdirectory(filetozip, zipedfile, password);
      }
      else if (file.exists(filetozip))
      {
        this.rootpath = path.getdirectoryname(filetozip);
        result = zipfile(filetozip, zipedfile, password);
      }
      return result;
    }
    /// <summary> 
    /// 压缩文件或文件夹 
    /// </summary> 
    /// <param name="filetozip">要压缩的路径</param> 
    /// <param name="zipedfile">压缩后的文件名</param> 
    /// <returns>压缩结果</returns> 
    public bool zip(string filetozip, string zipedfile)
    {
      bool result = zip(filetozip, zipedfile, null);
      return result;
    }
    #endregion
    #region 解压
    /// <summary> 
    /// 解压功能(解压压缩文件到指定目录) 
    /// </summary> 
    /// <param name="filetounzip">待解压的文件</param> 
    /// <param name="zipedfolder">指定解压目标目录</param> 
    /// <param name="password">密码</param> 
    /// <returns>解压结果</returns> 
    public bool unzip(string filetounzip, string zipedfolder, string password)
    {
      bool result = true;
      filestream fs = null;
      zipinputstream zipstream = null;
      zipentry ent = null;
      string filename;
      if (!file.exists(filetounzip))
        return false;
      if (!directory.exists(zipedfolder))
        directory.createdirectory(zipedfolder);
      try
      {
        zipstream = new zipinputstream(file.openread(filetounzip));
        if (!string.isnullorempty(password)) zipstream.password = password;
        while ((ent = zipstream.getnextentry()) != null)
        {
          if (!string.isnullorempty(ent.name))
          {
            filename = path.combine(zipedfolder, ent.name);
            filename = filename.replace('/', '\\');//change by mr.hopegi 
            if (filename.endswith("\\"))
            {
              directory.createdirectory(filename);
              continue;
            }
            fs = file.create(filename);
            int size = 2048;
            byte[] data = new byte[size];
            while (true)
            {
              size = zipstream.read(data, 0, data.length);
              if (size > 0)
                fs.write(data, 0, data.length);
              else
                break;
            }
          }
        }
      }
      catch
      {
        result = false;
      }
      finally
      {
        if (fs != null)
        {
          fs.close();
          fs.dispose();
        }
        if (zipstream != null)
        {
          zipstream.close();
          zipstream.dispose();
        }
        if (ent != null)
        {
          ent = null;
        }
        gc.collect();
        gc.collect(1);
      }
      return result;
    }
    /// <summary> 
    /// 解压功能(解压压缩文件到指定目录) 
    /// </summary> 
    /// <param name="filetounzip">待解压的文件</param> 
    /// <param name="zipedfolder">指定解压目标目录</param> 
    /// <returns>解压结果</returns> 
    public bool unzip(string filetounzip, string zipedfolder)
    {
      bool result = unzip(filetounzip, zipedfolder, null);
      return result;
    }
    #endregion
  }
}

备注

关于生成压缩的方法还有很多,如通过命令行调用winrar的执行文件,sharpziplib只是方法之一。

关于sharpziplib的的api文档,可参看链接

总结

以上所述是小编给大家介绍的c# 使用sharpziplib生成压缩包的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:https://www.cnblogs.com/hsiang/archive/2018/09/28/9721423.html

延伸 · 阅读

精彩推荐
  • C#C#设计模式之Visitor访问者模式解决长隆欢乐世界问题实例

    C#设计模式之Visitor访问者模式解决长隆欢乐世界问题实例

    这篇文章主要介绍了C#设计模式之Visitor访问者模式解决长隆欢乐世界问题,简单描述了访问者模式的定义并结合具体实例形式分析了C#使用访问者模式解决长...

    GhostRider9502022-01-21
  • C#深入解析C#中的交错数组与隐式类型的数组

    深入解析C#中的交错数组与隐式类型的数组

    这篇文章主要介绍了深入解析C#中的交错数组与隐式类型的数组,隐式类型的数组通常与匿名类型以及对象初始值设定项和集合初始值设定项一起使用,需要的...

    C#教程网6172021-11-09
  • C#C# 实现对PPT文档加密、解密及重置密码的操作方法

    C# 实现对PPT文档加密、解密及重置密码的操作方法

    这篇文章主要介绍了C# 实现对PPT文档加密、解密及重置密码的操作方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下...

    E-iceblue5012022-02-12
  • C#C#通过KD树进行距离最近点的查找

    C#通过KD树进行距离最近点的查找

    这篇文章主要为大家详细介绍了C#通过KD树进行距离最近点的查找,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    帆帆帆6112022-01-22
  • C#C#裁剪,缩放,清晰度,水印处理操作示例

    C#裁剪,缩放,清晰度,水印处理操作示例

    这篇文章主要为大家详细介绍了C#裁剪,缩放,清晰度,水印处理操作示例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    吴 剑8332021-12-08
  • C#C#实现XML文件读取

    C#实现XML文件读取

    这篇文章主要为大家详细介绍了C#实现XML文件读取的相关代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    Just_for_Myself6702022-02-22
  • C#WPF 自定义雷达图开发实例教程

    WPF 自定义雷达图开发实例教程

    这篇文章主要介绍了WPF 自定义雷达图开发实例教程,本文介绍的非常详细,具有参考借鉴价值,需要的朋友可以参考下...

    WinterFish13112021-12-06
  • C#Unity3D实现虚拟按钮控制人物移动效果

    Unity3D实现虚拟按钮控制人物移动效果

    这篇文章主要为大家详细介绍了Unity3D实现虚拟按钮控制人物移动效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一...

    shenqingyu060520232410972022-03-11