c#压缩和解压缩
项目上用到的,随手做个记录,哈哈。
直接上代码:

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 }

封装的很彻底,基本不用修改什么,直接拿来用就行了。
找了很久,终于知道怎么把源代码附上了
源代码:https://files.cnblogs.com/files/hahahayang/C%E5%8E%8B%E7%BC%A9%E6%96%87%E4%BB%B6.zip
c#压缩和解压缩的更多相关文章
- Linux下的压缩和解压缩命令——gzip/gunzip
gzip命令 gzip命令用来压缩文件.gzip是个使用广泛的压缩程序,文件经它压缩过后,其名称后面会多处".gz"扩展名. gzip是在Linux系统中经常使用的一个对文件进行压 ...
- Linux常用命令学习3---(文件的压缩和解压缩命令zip unzip tar、关机和重启命令shutdown reboot……)
1.压缩和解压缩命令 常用压缩格式:.zip..gz..bz2..tar.gz..tar.bz2..rar .zip格式压缩和解压缩命令 zip 压缩文件名 源文件:压缩文件 ...
- [Java 基础] 使用java.util.zip包压缩和解压缩文件
reference : http://www.open-open.com/lib/view/open1381641653833.html Java API中的import java.util.zip ...
- 关于webservice大数据量传输时的压缩和解压缩
当访问WebSerivice时,如果数据量很大,传输数据时就会很慢.为了提高速度,我们就会想到对数据进行压缩.首先我们来分析一下. 当在webserice中传输数据时,一般都采用Dataset进行数据 ...
- 重新想象 Windows 8 Store Apps (70) - 其它: 文件压缩和解压缩, 与 Windows 商店相关的操作, app 与 web, 几个 Core 的应用, 页面的生命周期和程序的生命周期
[源码下载] 重新想象 Windows 8 Store Apps (70) - 其它: 文件压缩和解压缩, 与 Windows 商店相关的操作, app 与 web, 几个 Core 的应用, 页面的 ...
- IOS开发之网络编程--文件压缩和解压缩
前言: QQ表情包就用到了解压缩,从网络下载的那么多表情文件格式并不是一个一个图片文件,而是多个图片压缩而成的表情压缩包.下面介绍的是iOS开发中会用到的压缩和解压缩的第三方框架的使用. 注意: 这个 ...
- 压缩和解压缩gz包
gz是Linux和OSX中常见的压缩文件格式,下面是用java压缩和解压缩gz包的例子 public class GZIPcompress { public static void FileCompr ...
- 在C#中利用SharpZipLib进行文件的压缩和解压缩收藏
我在做项目的时候需要将文件进行压缩和解压缩,于是就从http://www.icsharpcode.net(http://www.icsharpcode.net/OpenSource/SharpZipL ...
- C#- 压缩和解压缩的研究 .
用了第二种方法,感觉很不错,其他都没用过了.摘录下来,做一个备忘. 最近在网上查了一下在.net中进行压缩和解压缩的方法,方法有很多,我找到了以下几种: 1.利用.net自带的压缩和解压缩方法GZip ...
- .net中压缩和解压缩的处理
最近在网上查了一下在.net中进行压缩和解压缩的方法,方法有很多,我找到了以下几种: 1.利用.net自带的压缩和解压缩方法GZip 参考代码如下: //======================= ...
随机推荐
- LeetCode 232. 用栈实现队列(Implement Queue using Stacks) 4
232. 用栈实现队列 232. Implement Queue using Stacks 题目描述 使用栈实现队列的下列操作: push(x) -- 将一个元素放入队列的尾部. pop() -- 从 ...
- php创建生成数组的相关函数
php中和数组创建生成的函数有很多,用于定义数组的函数array(),数组合并函数array_combine(),还有array_fill(),array_fill_keys(),range()等等. ...
- 批量删除c文件和h文件中的注释
不知道大家有没有批量删除c文件和h文件中注释的需要,说起来搞笑,偶然翻出来早先写的一份,首先楼猪不是闲的蛋疼写这东西,工作需要,哪里要砖就要搬.冷门的东西大家需要的时候也不一定好找,分享给大家,省的自 ...
- BC26模组UDP调试
BC26模组调试 数据上报AT流程 [15:33:46.819]收←◆ F1: 0000 0000 V0: 0000 0000 [0001] 00: 0006 000C 01: 0000 0000 U ...
- flex左右布局 左边固定 右侧自适应
flex左右布局 左边固定 右侧自适应 想要保证自适应内容不超出容器怎么办. 通过为自适应的一侧设置width: 0;或者overflow: hidden;解决. 首先实现标题的布局,也很简单: &l ...
- Spring Boot 集成 Swagger生成接口文档
目的: Swagger是什么 Swagger的优点 Swagger的使用 Swagger是什么 官网(https://swagger.io/) Swagger 是一个规范和完整的框架,用于生成.描述. ...
- linux学习之路(二)--centos7安装Redis(单点)
一.安装redis 1.进入/usr/local/,新建services目录,进入该目录,下载redis wget http://download.redis.io/releases/redis-4. ...
- PAT-1111 Online Map (30分) 最短路+dfs
明天就要考PAT,为了应付期末已经好久没有刷题了啊啊啊啊,今天开了一道最短路,状态不是很好 1.没有读清题目要求,或者说没有读完题目,明天一定要注意 2.vis初始化的时候从1初始化到n,应该从0开始 ...
- 记录一次kafka解决相同userId顺序消费的问题
基本思路:在kafka生产者生产消息时,把相同userId的消息落在同一个分区/partition public void sendTopic1(String tpoic, String userId ...
- C# EF 加密连接数据库连接字符串
不多说,直接上代码 public partial class Model1 : DbContext { private static string connStr = ""; pu ...