SharpZipLib 文件/文件夹压缩

一、ZipFile

  ZipFile类用于选择文件或文件夹进行压缩生成压缩包。

  常用属性:

属性 说明
Count 文件数目(注意是在ComitUpdat之后才有)
Password 压缩包密码
Size 压缩包占用空间大小
Name 压缩包名称,默认输出是文件路径
ZipEntry 压缩包里的文件,通过索引[]访问

  其常用方法如下:

方法 说明
Add 添加要进行压缩的文件
AddDirectory 添加文件夹(不会压缩文件夹里的文件)
Delete 删除文件或文件夹
BeginUpdate 开始修改压缩包
CommitUpdate 提交修改
SetComment 添加注释

  示例1(创建压缩文件):

  using (ZipFile zip = ZipFile.Create(@"D:\test.zip"))
  {
zip.BeginUpdate();       zip.SetComment("这是我的压缩包");
zip.Add(@"D:\1.txt"); //添加一个文件
zip.AddDirectory(@"D:\2"); //添加一个文件夹(这个方法不会压缩文件夹里的文件)
zip.Add(@"D:\2\2.txt"); //添加文件夹里的文件
zip.CommitUpdate();
}

  这样生成的压缩包是包含子文件夹,子文件夹也是包含子文件的。

  其中,注释如下:

  

  示例2:修改压缩包

  using (ZipFile zip = new ZipFile(@"D:\test.zip"))
{
zip.BeginUpdate();
zip.Add(@"D:\2.txt");
zip.CommitUpdate();
}

  留意这个示例和上面的有什么不同,上面的是Create方法创建的ZipFile对象,而这里是直接读。因此,如果压缩包里面有文件,则不会改动原来的压缩文件,而是往会里面添加一个。这样就相当于压缩包的修改,而上面是压缩包的创建。

  示例3:读取压缩包里的文件:

  using (ZipFile zip = new ZipFile(@"D:\test.zip"))
{
foreach (ZipEntry z in zip)
{
Console.WriteLine(z);
}
ZipEntry z1 = zip[0];
Console.WriteLine(z1.Name);
}

二、FastZip

  这个类就两个方法:

方法 说明
CreateZip 压缩目录
ExtractZip 解压缩目录

  

  1、FastZip用于快速压缩目录,示例如下:

//快速压缩目录,包括目录下的所有文件
(new FastZip()).CreateZip(@"D:\test.zip", @"D:\test\", true, "");

  这个是递归压缩的。但是局限性就是只能压缩文件夹。

  否则报如下错误:

  

  2、快速解压缩目录

//快速解压
(new FastZip()).ExtractZip(@"D:\test.zip", @"D:\解压目录\", "");

三、ZipOutputStream与ZipEntry

  • ZipOutputStream:相当于一个压缩包;
  • ZipEntry:相当于压缩包里的一个文件;

  以上两个类是SharpZipLib的主类,最耐玩的就是这两个类。

  ZipOutputStream常用属性:

属性 说明
IsFinished ZipOutputStream是否已结束

  ZipOutputStream常用方法:

方法 说明
CloseEntry 关闭入口,关闭之后不允许再对ZipOutputStream进行操作
Finish 结束写入
GetLevel 读取压缩等级
PutNextEntry 往ZipOutputStream里写入一个ZipEntry
SetComment 压缩包的注释
SetLevel 设置压缩等级,等级越高文件越小
Write 写入文件内容

  使用ZipOutputStream创建一个压缩包并往里面写入一个文件的示例:

        static void Main(string[] args)
{
using (ZipOutputStream s = new ZipOutputStream(File.Create(@"D:\123.zip")))
{
s.SetLevel(6); //设置压缩等级,等级越高压缩效果越明显,但占用CPU也会更多using (FileStream fs = File.OpenRead(@"D:\1.txt"))
{
byte[] buffer = new byte[4 * 1024]; //缓冲区,每次操作大小
ZipEntry entry = new ZipEntry(Path.GetFileName(@"改名.txt")); //创建压缩包内的文件
entry.DateTime = DateTime.Now; //文件创建时间
s.PutNextEntry(entry); //将文件写入压缩包 int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length); //读取文件内容(1次读4M,写4M)
s.Write(buffer, 0, sourceBytes); //将文件内容写入压缩相应的文件
} while (sourceBytes > 0);
}
s.CloseEntry();
} Console.ReadKey();
}

  以上示例仅仅能够压缩文件,要压缩文件夹就要使用递归的方式,循环子目录并压缩子目录里的文件。

  示例2:文件夹压缩,保持原文件夹架构:

    class Program
{
static void Main(string[] args)
{
string Source = @"D:\test";
string TartgetFile = @"D:\test.zip";
Directory.CreateDirectory(Path.GetDirectoryName(TartgetFile));
using (ZipOutputStream s = new ZipOutputStream(File.Create(TartgetFile)))
{
s.SetLevel(6);
Compress(Source, s);
s.Finish();
s.Close();
} Console.ReadKey();
} /// <summary>
/// 压缩
/// </summary>
/// <param name="source">源目录</param>
/// <param name="s">ZipOutputStream对象</param>
public static void Compress(string source, ZipOutputStream s)
{
string[] filenames = Directory.GetFileSystemEntries(source);
foreach (string file in filenames)
{
if (Directory.Exists(file))
{
Compress(file, s); //递归压缩子文件夹
}
else
{
using (FileStream fs = File.OpenRead(file))
{
byte[] buffer = new byte[4 * 1024];
ZipEntry entry = new ZipEntry(file.Replace(Path.GetPathRoot(file),"")); //此处去掉盘符,如D:\123\1.txt 去掉D:
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry); int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
}
}
}

  附上解压缩方法:

        /// <summary>
/// 解压缩
/// </summary>
/// <param name="sourceFile">源文件</param>
/// <param name="targetPath">目标路经</param>
public bool Decompress(string sourceFile, string targetPath)
{
if (!File.Exists(sourceFile))
{
throw new FileNotFoundException(string.Format("未能找到文件 '{0}' ", sourceFile));
}
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
using (ZipInputStream s = new ZipInputStream(File.OpenRead(sourceFile)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directorName = Path.Combine(targetPath, Path.GetDirectoryName(theEntry.Name));
string fileName = Path.Combine(directorName, Path.GetFileName(theEntry.Name));
// 创建目录
if (directorName.Length > 0)
{
Directory.CreateDirectory(directorName);
}
if (fileName != string.Empty)
{
using (FileStream streamWriter = File.Create(fileName))
{
int size = 4096;
byte[] data = new byte[ 4 * 1024];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else break;
}
}
}
}
}
return true;
}

  ZipEntry就没什么好说的了,都是一些属性,指示一下,实际用到的很少。

转自:http://www.cnblogs.com/kissdodog/p/3525295.html

c#操作Zip压缩文件的更多相关文章

  1. php操作zip压缩文件

    php操作zip压缩文件 一.总结 1.php操作zip:php可以操作zip压缩文件,通过 ZZIPLIB扩展库,这些扩展库可以通过composer安装,或者某些版本的php会自带 2.完美操作zi ...

  2. 【VC++技术杂谈008】使用zlib解压zip压缩文件

    最近因为项目的需要,要对zip压缩文件进行批量解压.在网上查阅了相关的资料后,最终使用zlib开源库实现了该功能.本文将对zlib开源库进行简单介绍,并给出一个使用zlib开源库对zip压缩文件进行解 ...

  3. java ZIP压缩文件

    问题描述:     使用java ZIP压缩文件和目录 问题解决:     (1)单个文件压缩 注:     以上是实现单个文件写入压缩包的代码,注意其中主要是在ZipOutStream流对象中创建Z ...

  4. PHP zip压缩文件及解压

    PHP zip压缩文件及解压 利用ZipArchive 类实现 只有有函数.界面大家自己写 ZipArchive(PHP 5.3 + 已自带不需要安装dll) /** * 文件解压 * @param ...

  5. php实现ZIP压缩文件解压缩

    测试使用了两个办法都可以实现: 第一个:需要开启配置php_aip.dll <?php //需开启配置 php_zip.dll //phpinfo(); header("Content ...

  6. java将文件打包成ZIP压缩文件的工具类实例

    package com.lanp; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import ja ...

  7. php实现ZIP压缩文件解压缩(转)

    测试使用了两个办法都可以实现: 第一个:需要开启配置php_aip.dll <?php //需开启配置 php_zip.dll //phpinfo(); header("Content ...

  8. Python 黑客 --- 002 入门级 ZIP压缩文件口令暴力破解机

    Python 黑客 入门级实战:ZIP压缩文件口令暴力破解机 使用的系统:Ubuntu 14.04 LTS Python语言版本:Python 2.7.10 V 编写zip 压缩文件口令破解器需要使用 ...

  9. PHP生成ZIP压缩文件

    PHP生成ZIP压缩文件 /* * 生成zip压缩文件 * $sourceDir:被压缩的文件夹或文件 * $outFileName:输出的压缩文件名称 * */ function createZip ...

随机推荐

  1. java小程序实例 闰年

    判断闰年. package com.test; import java.util.Scanner; import org.junit.Test; public class TestRunNian { ...

  2. C Primer Plus(第五版)5

    第5章 运算符,表达式和语句 5.1 循环简单 程序清单 5.1 显示了一个示例程序,该程序做了一点算术运算来计算穿 9 码鞋的脚用英寸表示的长度.为了增加你对循环的理解,程序的第一版演示了不使用循环 ...

  3. Machine Schedule(最小覆盖)

    其实也是个最小覆盖问题 关于最小覆盖http://blog.csdn.net/u014665013/article/details/49870029 Description As we all kno ...

  4. 【转】find命令

    Linux中find常见用法示例·find path -option [ -print ] [ -exec -ok command ] {} \;find命令的参数: pathname: find命令 ...

  5. kylin一种OLAP的实现

    1.基于hive.hadoop的预先计算. 2.cube存储在HBASE里面.利用HBase的列存储,实现MOLAP 3.在cube上做数据分析,kylin实现标准的SQL,实现查询HBase 所以说 ...

  6. AOP切入点注解报错

    开始学习AOP,出现如下的错误,最后发现是JDK与aspectj,aspectjweaver版本问题造成的.之后改成最新版本,代码运行正常. 利用这些特性可以进行代码的插入,比如权限,缓存结合mecm ...

  7. PHP 文件读取 fread、fgets、fgetc、file_get_contents 与 file 函数

    fread().fgets().fgetc().file_get_contents() 与 file() 函数用于从文件中读取内容. fread() fread() 函数用于读取文件(可安全用于二进制 ...

  8. 访问控制符private,default,protect和public

    程序,通过封装以实现"高内聚,内耦合". 个人理解,类内,包内,子类和所有类,是java的四个范围. private表示作用区域为类内,即只是自己(像牙刷). default表示作 ...

  9. Redis数据持久化之AOF持久化

    一.RDB持久化的缺点创建RDB文件需要将服务器所有的数据库的数据都保存起来,这是一个非常耗费资源和时间的操作,所以服务器需要隔一段时间才能创建一个新的RDB文件,就也是说创建RDB文件的操作不能执行 ...

  10. php操作mysql的基础链接实例