C#工具类:使用SharpZipLib进行压缩、解压文件
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进行压缩、解压文件的更多相关文章
- 通过SharpZipLib来压缩解压文件
在项目开发中,一些比较常用的功能就是压缩解压文件了,其实类似的方法有许多 ,现将通过第三方类库SharpZipLib来压缩解压文件的方法介绍如下,主要目的是方便以后自己阅读,当然可以帮到有需要的朋友更 ...
- .NET使用ICSharpCode.SharpZipLib压缩/解压文件
SharpZipLib是国外开源加压解压库,可以方便的对文件进行加压/解压 1.下载ICSharpCode.SharpZipLib.dll,并复制到bin目录下 http://www.icsharpc ...
- C#使用SharpZipLib压缩解压文件
#region 加压解压方法 /// <summary> /// 功能:压缩文件(暂时只压缩文件夹下一级目录中的文件,文件夹及其子级被忽略) /// </summary> // ...
- 【转载】.NET压缩/解压文件/夹组件
转自:http://www.cnblogs.com/asxinyu/archive/2013/03/05/2943696.html 阅读目录 1.前言 2.关于压缩格式和算法的基础 3.几种常见的.N ...
- huffman压缩解压文件【代码】
距离上次写完哈夫曼编码已经过去一周了,这一周都在写huffman压缩解压,哎,在很多小错误上浪费了很多时间调bug.其实这个程序的最关键部分不是我自己想的,而是借鉴了某位园友的代码,但是,无论如何,自 ...
- Ubuntu下压缩解压文件
一般来说ubuntu 下带有tar 命令,可以用来解压和压缩之用.但是我们经常要与win下用户打交道,所以要安装一些解压工具如:rar zip 等命令. 如果要需要用到zip工具那么可以: sudo ...
- [转]Ubuntu16 压缩解压文件命令
原文地址:http://blog.csdn.net/feibendexiaoma/article/details/73739279,转载主要方便随时查阅,如有版权要求,请及时联系. ZIP zip是比 ...
- linux压缩解压文件
首先进入文件夹 cd /home/ftp2/1520/web 压缩方法一:压缩web下的888.com网站 zip -r 888.com.zip888.com 压缩方法二:将当前目录下的所有文件和文件 ...
- Freebsd下压缩解压文件详解
压缩篇: 把/usr/webgames目录下的文件打包.命名为bak.tar.gz 放到/usr/db-bak目录里 下面命令可以在任意目录执行.无视当前目录和将要存放文件的目录.tar -zcvf ...
- 跨平台的zip文件压缩处理,支持压缩解压文件夹
根据minizip改写的模块,需要zlib支持 输出的接口: #define RG_ZIP_FILE_REPLACE 0 #define RG_ZIP_FILE_APPEND 1 //压缩文件夹目录, ...
随机推荐
- fiddler中断request,修改参数问题
fiddler正在学习阶段,遇到了一个问题,就是bpu url后,不会修改参数,今天实验了几次,总算成功了 下面写一下步骤: 1.先打开fiddler 2.打开网站,如百度,在文本框输入1,记住!不要 ...
- angular-控制器
controller 控制器 四.作用域:($rootScope)对整个页面相当于全局变量 也就是只要是用$rootScope定的东西它一定是作用于全局,而其它的只是对它控制器所在的那一部分 列如: ...
- IntelliJ IDEA小问题通过操作软件解决
Diamond types are not supported at this language level http://blog.csdn.net/qq_34884729/article/deta ...
- QEMU KVM libvirt 手册(1): 安装
安装 对虚拟化的支持通常在BIOS中是禁掉的,必须开启才可以. 对于Intel CPU,我们可以通过下面的命令查看是否支持虚拟化. # grep "vmx" /proc/cpuin ...
- 【备忘】EntityFramework 6 升级到 EntityFrameworkCore 注意点
正在将一个 .net framework 4.5 的项目升级到 .net core 2.1,其中使用到了 EF6,经历了一些修改: 命名空间的变化基本上可以靠自动提示补充完整,不需要强记. DbQue ...
- 目标检测算法(1)目标检测中的问题描述和R-CNN算法
目标检测(object detection)是计算机视觉中非常具有挑战性的一项工作,一方面它是其他很多后续视觉任务的基础,另一方面目标检测不仅需要预测区域,还要进行分类,因此问题更加复杂.最近的5年使 ...
- Python 爬虫修养-处理动态网页
Python 爬虫修养-处理动态网页 本文转自:i春秋社区 0x01 前言 在进行爬虫开发的过程中,我们会遇到很多的棘手的问题,当然对于普通的问题比如 UA 等修改的问题,我们并不在讨论范围,既然要将 ...
- 酷炫,用Html5/CSS实现文字阴影
前两天有一个学html5前端小美女问我一个有关文字阴影的效果怎么去实现.她和我说文字阴影嘛,她也知道text-shadow,.但是却做不出想要的样子,其实css3的新功能是很强大的,不要把你的思想太过 ...
- 打开Python IDLE时的错误:Subprocess Startup Error
比较常见的是这个 方法1: 修改[Python目录]\Lib\idlelib\PyShell.py文件,在1300行附近,将def main():函数下面 use_subprocess = True ...
- Android之Activity系列总结(二)--任务和返回栈
任务和返回栈 应用通常包含多个 Activity.每个 Activity 均应围绕用户可以执行的特定操作设计,并且能够启动其他 Activity. 例如,电子邮件应用可能有一个 Activity 显示 ...