前言
8 S1 t$ o. {- I* _! Y7 x- a在我们项目开发中,经常需要解压缩功能,用来减少网络带宽、磁盘空间等,但是如果自己开发,需要掌握诸多知识,比如:压缩算法、兼容性等。给大家推荐一个解压缩开源库,让你轻松完成解压缩文件的功能。
7 V1 K+ e+ V1 x' f$ |项目简介" g# t, K9 A0 z) E1 a
这个一个完全由C#开发的、具备压缩和解压缩的功能,支持Zip,GZip,Tar和BZip2等格式,方便你集成到各种.NET项目中。
9 b& ^ y/ B- a, j+ a6 j9 R项目特点% A, a2 [8 @ F, h% z, W
1、完全开源和免费:也可以根据自己的需求,自行编译源码;1 V. r z& W# H- b; A# \! H2 _
2、跨平台:支持Windows、Linux和Mac OS) f( K3 h% P A0 b& Z! O
3、灵活且易于使用:提供了多种压缩和解压缩的功能,包括读取和解压zip文件、写入zip文件、解压GZip文件、读取和解压tar文件等+ @. Z0 s" ]% C
4、高性能:性能接近于系统的压缩工具,但提供了更为方便的API。
. T. C+ Q/ q0 B" n) v; r3 A示例代码( ^# H( f3 u! s6 t1 X! ~0 U, M
using ICSharpCode.SharpZipLib.Zip;
//设置密码
var password = "123456";
//压缩后的文件名称
string zipFileName = "1.zip";
//要压缩的目录
string sourceDirectory = "E:\\file";
//是否压缩子目录
bool recurse = true;
//过滤文件
string fileFilter = "";
//压缩文件
FastZip fastZip = new FastZip();
fastZip.Password = password;
fastZip.CreateEmptyDirectories = true;
fastZip.CreateZip(zipFileName, sourceDirectory, recurse, fileFilter);
//查看压缩后的大小
using (ZipFile zFile = new ZipFile(zipFileName))
{
Console.WriteLine("查看文件 : " + zFile.Name);
Console.WriteLine("");
Console.WriteLine("原始大小 大小 日期 时间 文件名");
Console.WriteLine("-------- -------- -------- ------ ---------");
foreach (ZipEntry e in zFile)
{
if (e.IsFile)
{
DateTime d = e.DateTime;
Console.WriteLine("{0, -10}{1, -10}{2} {3} {4}", e.Size, e.CompressedSize,
d.ToString("dd-MM-yy"), d.ToString("HH:mm"),
e.Name);
}
}
} 效果7 f, Y' u2 U2 S6 v' L: W3 K' L
6 z0 D r- e* I项目地址
6 U4 _$ Q a8 A4 g7 b- |https://github.com/icsharpcode/SharpZipLib |