SharpZipLib是一个开源的C#压缩解压库,应用非常广泛。就像用ADO.NET操作数据库要打开连接、执行命令、关闭连接等多个步骤一样,用SharpZipLib进行压缩和解压也需要多个步骤。SharpZipLib功能比较强大,在很多C#的应用中,都有它的身影,我们可以通过引入SharpZipLib类库文件,在程序中实现自动压缩文件以及解压缩文件的功能,例如一个常见的情景就是用户客户端程序下载更新包,下载完成之后,在本地自动解压文件。

SharpZipLib的官方地址是:http://icsharpcode.github.io/SharpZipLib/,实际使用可以通过NuGet获取,在NuGet的地址是:http://www.nuget.org/packages/SharpZipLib/

在这个封装好的解压缩工具类中,我们引用了SharpZipLib组件,实现了解压缩.Zip文件格式的压缩文件,允许指定解压缩的路径。具体实现如下:

 public class SharpZip
{
public SharpZip()
{ }
/// <summary>
/// 压缩
/// </summary>
/// <param name="filename"> 压缩后的文件名(包含物理路径)</param>
/// <param name="directory">待压缩的文件夹(包含物理路径)</param>
public static void PackFiles(string filename, string directory)
{
try
{
FastZip fz = new FastZip();
fz.CreateEmptyDirectories = true;
fz.CreateZip(filename, directory, true, "");
fz = null;
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// 解压缩
/// </summary>
/// <param name="file">待解压文件名(包含物理路径)</param>
/// <param name="dir"> 解压到哪个目录中(包含物理路径)</param>
public static bool UnpackFiles(string file, string dir)
{
try
{
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
ZipInputStream s = new ZipInputStream(File.OpenRead(file));
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
if (directoryName != String.Empty)
{
Directory.CreateDirectory(dir + directoryName);
}
if (fileName != String.Empty)
{
FileStream streamWriter = File.Create(dir + theEntry.Name);
int size = ;
byte[] data = new byte[];
while (true)
{
size = s.Read(data, , data.Length);
if (size > )
{
streamWriter.Write(data, , size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
s.Close();
return true;
}
catch (Exception)
{
throw;
}
}
}
public class ClassZip
{
#region 私有方法
/// <summary>
/// 递归压缩文件夹方法
/// </summary>
private static bool ZipFileDictory(string FolderToZip, ZipOutputStream s, string ParentFolderName)
{
bool res = true;
string[] folders, filenames;
ZipEntry entry = null;
FileStream fs = null;
Crc32 crc = new Crc32();
try
{
entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/"));
s.PutNextEntry(entry);
s.Flush();
filenames = Directory.GetFiles(FolderToZip);
foreach (string file in filenames)
{
fs = File.OpenRead(file);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, , buffer.Length);
entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/" + Path.GetFileName(file)));
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
s.PutNextEntry(entry);
s.Write(buffer, , buffer.Length);
}
}
catch
{
res = false;
}
finally
{
if (fs != null)
{
fs.Close();
fs = null;
}
if (entry != null)
{
entry = null;
}
GC.Collect();
GC.Collect();
}
folders = Directory.GetDirectories(FolderToZip);
foreach (string folder in folders)
{
if (!ZipFileDictory(folder, s, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip))))
{
return false;
}
}
return res;
}
/// <summary>
/// 压缩目录
/// </summary>
/// <param name="FolderToZip">待压缩的文件夹,全路径格式</param>
/// <param name="ZipedFile">压缩后的文件名,全路径格式</param>
private static bool ZipFileDictory(string FolderToZip, string ZipedFile, int level)
{
bool res;
if (!Directory.Exists(FolderToZip))
{
return false;
}
ZipOutputStream s = new ZipOutputStream(File.Create(ZipedFile));
s.SetLevel(level);
res = ZipFileDictory(FolderToZip, s, "");
s.Finish();
s.Close();
return res;
}
/// <summary>
/// 压缩文件
/// </summary>
/// <param name="FileToZip">要进行压缩的文件名</param>
/// <param name="ZipedFile">压缩后生成的压缩文件名</param>
private static bool ZipFile(string FileToZip, string ZipedFile, int level)
{
if (!File.Exists(FileToZip))
{
throw new System.IO.FileNotFoundException("指定要压缩的文件: " + FileToZip + " 不存在!");
}
FileStream ZipFile = null;
ZipOutputStream ZipStream = null;
ZipEntry ZipEntry = null;
bool res = true;
try
{
ZipFile = File.OpenRead(FileToZip);
byte[] buffer = new byte[ZipFile.Length];
ZipFile.Read(buffer, , buffer.Length);
ZipFile.Close();
ZipFile = File.Create(ZipedFile);
ZipStream = new ZipOutputStream(ZipFile);
ZipEntry = new ZipEntry(Path.GetFileName(FileToZip));
ZipStream.PutNextEntry(ZipEntry);
ZipStream.SetLevel(level);
ZipStream.Write(buffer, , buffer.Length);
}
catch
{
res = false;
}
finally
{
if (ZipEntry != null)
{
ZipEntry = null;
}
if (ZipStream != null)
{
ZipStream.Finish();
ZipStream.Close();
}
if (ZipFile != null)
{
ZipFile.Close();
ZipFile = null;
}
GC.Collect();
GC.Collect();
}
return res;
}
#endregion
/// <summary>
/// 压缩
/// </summary>
/// <param name="FileToZip">待压缩的文件目录</param>
/// <param name="ZipedFile">生成的目标文件</param>
/// <param name="level"></param>
public static bool Zip(String FileToZip, String ZipedFile, int level)
{
if (Directory.Exists(FileToZip))
{
return ZipFileDictory(FileToZip, ZipedFile, level);
}
else if (File.Exists(FileToZip))
{
return ZipFile(FileToZip, ZipedFile, level);
}
else
{
return false;
}
}
/// <summary>
/// 解压
/// </summary>
/// <param name="FileToUpZip">待解压的文件</param>
/// <param name="ZipedFolder">解压目标存放目录</param>
public static void UnZip(string FileToUpZip, string ZipedFolder)
{
if (!File.Exists(FileToUpZip))
{
return;
}
if (!Directory.Exists(ZipedFolder))
{
Directory.CreateDirectory(ZipedFolder);
}
ZipInputStream s = null;
ZipEntry theEntry = null;
string fileName;
FileStream streamWriter = null;
try
{
s = new ZipInputStream(File.OpenRead(FileToUpZip));
while ((theEntry = s.GetNextEntry()) != null)
{
if (theEntry.Name != String.Empty)
{
fileName = Path.Combine(ZipedFolder, theEntry.Name);
if (fileName.EndsWith("/") || fileName.EndsWith("\\"))
{
Directory.CreateDirectory(fileName);
continue;
}
streamWriter = File.Create(fileName);
int size = ;
byte[] data = new byte[];
while (true)
{
size = s.Read(data, , data.Length);
if (size > )
{
streamWriter.Write(data, , size);
}
else
{
break;
}
}
}
}
}
finally
{
if (streamWriter != null)
{
streamWriter.Close();
streamWriter = null;
}
if (theEntry != null)
{
theEntry = null;
}
if (s != null)
{
s.Close();
s = null;
}
GC.Collect();
GC.Collect();
}
}
}
public class ZipHelper
{
#region 私有变量
String the_rar;
RegistryKey the_Reg;
Object the_Obj;
String the_Info;
ProcessStartInfo the_StartInfo;
Process the_Process;
#endregion
/// <summary>
/// 压缩
/// </summary>
/// <param name="zipname">要解压的文件名</param>
/// <param name="zippath">要压缩的文件目录</param>
/// <param name="dirpath">初始目录</param>
public void EnZip(string zipname, string zippath, string dirpath)
{
try
{
the_Reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\Shell\Open\Command");
the_Obj = the_Reg.GetValue("");
the_rar = the_Obj.ToString();
the_Reg.Close();
the_rar = the_rar.Substring(, the_rar.Length - );
the_Info = " a " + zipname + " " + zippath;
the_StartInfo = new ProcessStartInfo();
the_StartInfo.FileName = the_rar;
the_StartInfo.Arguments = the_Info;
the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
the_StartInfo.WorkingDirectory = dirpath;
the_Process = new Process();
the_Process.StartInfo = the_StartInfo;
the_Process.Start();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 解压缩
/// </summary>
/// <param name="zipname">要解压的文件名</param>
/// <param name="zippath">要解压的文件路径</param>
public void DeZip(string zipname, string zippath)
{
try
{
the_Reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRar.exe\Shell\Open\Command");
the_Obj = the_Reg.GetValue("");
the_rar = the_Obj.ToString();
the_Reg.Close();
the_rar = the_rar.Substring(, the_rar.Length - );
the_Info = " X " + zipname + " " + zippath;
the_StartInfo = new ProcessStartInfo();
the_StartInfo.FileName = the_rar;
the_StartInfo.Arguments = the_Info;
the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
the_Process = new Process();
the_Process.StartInfo = the_StartInfo;
the_Process.Start();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}

扩展阅读:C#工具类:使用iTextSharp操作PDF文档

备注:此文章转载自博主个人技术站点:IT技术小趣屋。原文链接:查看原文

博主个人技术交流群:960640092,博主微信公众号如下:

C#工具类:使用SharpZipLib进行压缩、解压文件的更多相关文章

  1. 通过SharpZipLib来压缩解压文件

    在项目开发中,一些比较常用的功能就是压缩解压文件了,其实类似的方法有许多 ,现将通过第三方类库SharpZipLib来压缩解压文件的方法介绍如下,主要目的是方便以后自己阅读,当然可以帮到有需要的朋友更 ...

  2. .NET使用ICSharpCode.SharpZipLib压缩/解压文件

    SharpZipLib是国外开源加压解压库,可以方便的对文件进行加压/解压 1.下载ICSharpCode.SharpZipLib.dll,并复制到bin目录下 http://www.icsharpc ...

  3. C#使用SharpZipLib压缩解压文件

    #region 加压解压方法 /// <summary> /// 功能:压缩文件(暂时只压缩文件夹下一级目录中的文件,文件夹及其子级被忽略) /// </summary> // ...

  4. 【转载】.NET压缩/解压文件/夹组件

    转自:http://www.cnblogs.com/asxinyu/archive/2013/03/05/2943696.html 阅读目录 1.前言 2.关于压缩格式和算法的基础 3.几种常见的.N ...

  5. huffman压缩解压文件【代码】

    距离上次写完哈夫曼编码已经过去一周了,这一周都在写huffman压缩解压,哎,在很多小错误上浪费了很多时间调bug.其实这个程序的最关键部分不是我自己想的,而是借鉴了某位园友的代码,但是,无论如何,自 ...

  6. Ubuntu下压缩解压文件

    一般来说ubuntu 下带有tar 命令,可以用来解压和压缩之用.但是我们经常要与win下用户打交道,所以要安装一些解压工具如:rar zip 等命令. 如果要需要用到zip工具那么可以: sudo ...

  7. [转]Ubuntu16 压缩解压文件命令

    原文地址:http://blog.csdn.net/feibendexiaoma/article/details/73739279,转载主要方便随时查阅,如有版权要求,请及时联系. ZIP zip是比 ...

  8. linux压缩解压文件

    首先进入文件夹 cd /home/ftp2/1520/web 压缩方法一:压缩web下的888.com网站 zip -r 888.com.zip888.com 压缩方法二:将当前目录下的所有文件和文件 ...

  9. Freebsd下压缩解压文件详解

    压缩篇: 把/usr/webgames目录下的文件打包.命名为bak.tar.gz 放到/usr/db-bak目录里 下面命令可以在任意目录执行.无视当前目录和将要存放文件的目录.tar -zcvf ...

  10. 跨平台的zip文件压缩处理,支持压缩解压文件夹

    根据minizip改写的模块,需要zlib支持 输出的接口: #define RG_ZIP_FILE_REPLACE 0 #define RG_ZIP_FILE_APPEND 1 //压缩文件夹目录, ...

随机推荐

  1. css中文字超出文本框,溢出部分用点点点表示

        text-overflow 属性规定当文本溢出包含元素时发生的事情.我们可以使用它来对文本超出的部分进行样式的处理. text-overflow: clip|ellipsis|string;包 ...

  2. FPGA跨时钟域握手信号的结构

    FPGA跨时钟数据传输,是我们经常遇到的问题的,下面给出一种跨时钟握手操作的电路结构.先上图 先对与其他人的结构,这个结构最大的特点是使用 req 从低到高或者高到低的变化 来表示DIN数据有效并开始 ...

  3. Centos6.5---samba文件共享服务配置(一)

    Linux---------samba文件共享服务配置(一) samba是一个实现不同操作系统之间文件共享和打印机共享的一种SMB协议的免费软件. https://www.cnblogs.com/zo ...

  4. 关于iOS与html交互,隐藏或修改html标签内容

    wkwebview 1.隐藏顶部标题栏 [webView evaluateJavaScript:@"document.getElementsByClassName('page-header' ...

  5. Cannot load php5apache2_4.dll into server

    配置PHP开发环境的时候,当进行到在Apache的httpd.conf文件中配置加载PHP模块时发生如下错误 httpd: Syntax error on line 185 of D:/wamp/Ap ...

  6. Kali学习笔记19:NESSUS安装及使用

    Nessus 百度百科:Nessus 是目前全世界最多人使用的系统漏洞扫描与分析软件.总共有超过75,000个机构使用Nessus 作为扫描该机构电脑系统的软件. 就我而言:漏洞扫描方面最强大的工具之 ...

  7. Kali学习笔记14:SMB扫描、SMTP扫描

    SMB(Server Message Block)协议,服务消息块协议. 最开始是用于微软的一种消息传输协议,因为颇受欢迎,现在已经成为跨平台的一种消息传输协议. 同时也是微软历史上出现安全问题最多的 ...

  8. while(true)应用之 实现自己的消息队列

    早些时候,一直有个疑问,就是比如你从前端发一个操作之后,后台为什么能够及时处理你的东西呢?当然了,我说的不是,服务器为什么能够立即接收到你的请求之类高大上的东西.而是,假设你用异步去做一个事情,而后台 ...

  9. java基础-3

    java基础-3 API ​ Application Programming Interfaces --- 应用程序接口 Object 顶级父类 Bin --- 二进制 Oct --- 八进制 Dec ...

  10. .NET图平台下的图像处理工具---强大的Emgucv

    图像一直与时代相伴,图形化的应用软件也重不可缺.对于MFC.Delphi.Lazarus.Qt大家可能已经耳熟能详.对于很多图像处理的开源库,很多都是用C\C++写的,而.Net下的开源库以前很少了解 ...