C#压缩库SharpZipLib的应用

/// <summary>
/// 压缩多个文件/文件夹
/// </summary>
/// <param name="sourceList">源文件/文件夹路径列表</param>
/// <param name="zipFilePath">压缩文件路径</param>
/// <param name="comment">注释信息</param>
/// <param name="password">压缩密码</param>
/// <param name="compressionLevel">压缩等级,范围从0到9,可选,默认为6</param>
/// <returns></returns>
public static bool CompressFile(IEnumerable<string> sourceList, string zipFilePath,
string comment = null, string password = null, int compressionLevel = )
{
bool result = false; try
{
//检测目标文件所属的文件夹是否存在,如果不存在则建立
string zipFileDirectory = Path.GetDirectoryName(zipFilePath);
if (!Directory.Exists(zipFileDirectory))
{
Directory.CreateDirectory(zipFileDirectory);
} Dictionary<string, string> dictionaryList = PrepareFileSystementities(sourceList); using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipFilePath)))
{
zipStream.Password = password;//设置密码
zipStream.SetComment(comment);//添加注释
zipStream.SetLevel(CheckCompressionLevel(compressionLevel));//设置压缩等级 foreach (string key in dictionaryList.Keys)//从字典取文件添加到压缩文件
{
if (File.Exists(key))//判断是文件还是文件夹
{
FileInfo fileItem = new FileInfo(key); using (FileStream readStream = fileItem.Open(FileMode.Open,
FileAccess.Read, FileShare.Read))
{
ZipEntry zipEntry = new ZipEntry(dictionaryList[key]);
zipEntry.DateTime = fileItem.LastWriteTime;
zipEntry.Size = readStream.Length;
zipStream.PutNextEntry(zipEntry);
int readLength = ;
byte[] buffer = new byte[BufferSize]; do
{
readLength = readStream.Read(buffer, , BufferSize);
zipStream.Write(buffer, , readLength);
} while (readLength == BufferSize); readStream.Close();
}
}
else//对文件夹的处理
{
ZipEntry zipEntry = new ZipEntry(dictionaryList[key] + "/");
zipStream.PutNextEntry(zipEntry);
}
} zipStream.Flush();
zipStream.Finish();
zipStream.Close();
} result = true;
}
catch (System.Exception ex)
{
throw new Exception("压缩文件失败", ex);
} return result;
} /// <summary>
/// 解压文件到指定文件夹
/// </summary>
/// <param name="sourceFile">压缩文件</param>
/// <param name="destinationDirectory">目标文件夹,如果为空则解压到当前文件夹下</param>
/// <param name="password">密码</param>
/// <returns></returns>
public static bool DecomparessFile(string sourceFile, string destinationDirectory = null, string password = null)
{
bool result = false; if (!File.Exists(sourceFile))
{
throw new FileNotFoundException("要解压的文件不存在", sourceFile);
} if (string.IsNullOrWhiteSpace(destinationDirectory))
{
destinationDirectory = Path.GetDirectoryName(sourceFile);
} try
{
if (!Directory.Exists(destinationDirectory))
{
Directory.CreateDirectory(destinationDirectory);
} using (ZipInputStream zipStream = new ZipInputStream(File.Open(sourceFile, FileMode.Open,
FileAccess.Read, FileShare.Read)))
{
zipStream.Password = password;
ZipEntry zipEntry = zipStream.GetNextEntry(); while (zipEntry != null)
{
if (zipEntry.IsDirectory)//如果是文件夹则创建
{
Directory.CreateDirectory(Path.Combine(destinationDirectory,
Path.GetDirectoryName(zipEntry.Name)));
}
else
{
string fileName = Path.GetFileName(zipEntry.Name);
if (!string.IsNullOrEmpty(fileName) && fileName.Trim().Length > )
{
FileInfo fileItem = new FileInfo(Path.Combine(destinationDirectory, zipEntry.Name));
using (FileStream writeStream = fileItem.Create())
{
byte[] buffer = new byte[BufferSize];
int readLength = ; do
{
readLength = zipStream.Read(buffer, , BufferSize);
writeStream.Write(buffer, , readLength);
} while (readLength == BufferSize); writeStream.Flush();
writeStream.Close();
}
fileItem.LastWriteTime = zipEntry.DateTime;
}
}
zipEntry = zipStream.GetNextEntry();//获取下一个文件
} zipStream.Close();
}
result = true;
}
catch (System.Exception ex)
{
throw new Exception("文件解压发生错误", ex);
} return result;
}
/// <summary>
/// 为压缩准备文件系统对象
/// </summary>
/// <param name="sourceFileEntityPathList"></param>
/// <returns></returns>
private static Dictionary<string, string> PrepareFileSystementities(IEnumerable<string> sourceFileEntityPathList)
{
Dictionary<string, string> fileEntityDictionary = new Dictionary<string, string>();//文件字典
string parentDirectoryPath = "";
foreach (string fileEntityPath in sourceFileEntityPathList)
{
string path = fileEntityPath;
//保证传入的文件夹也被压缩进文件
if (path.EndsWith(@"\"))
{
path = path.Remove(path.LastIndexOf(@"\"));
} parentDirectoryPath = Path.GetDirectoryName(path) + @"\"; if (parentDirectoryPath.EndsWith(@":\\"))//防止根目录下把盘符压入的错误
{
parentDirectoryPath = parentDirectoryPath.Replace(@"\\", @"\");
} //获取目录中所有的文件系统对象
Dictionary<string, string> subDictionary = GetAllFileSystemEntities(path, parentDirectoryPath); //将文件系统对象添加到总的文件字典中
foreach (string key in subDictionary.Keys)
{
if (!fileEntityDictionary.ContainsKey(key))//检测重复项
{
fileEntityDictionary.Add(key, subDictionary[key]);
}
}
}
return fileEntityDictionary;
} /// <summary>
/// 获取所有文件系统对象
/// </summary>
/// <param name="source">源路径</param>
/// <param name="topDirectory">顶级文件夹</param>
/// <returns>字典中Key为完整路径,Value为文件(夹)名称</returns>
private static Dictionary<string, string> GetAllFileSystemEntities(string source, string topDirectory)
{
Dictionary<string, string> entitiesDictionary = new Dictionary<string, string>();
entitiesDictionary.Add(source, source.Replace(topDirectory, "")); if (Directory.Exists(source))
{
//一次性获取下级所有目录,避免递归
string[] directories = Directory.GetDirectories(source, "*.*", SearchOption.AllDirectories);
foreach (string directory in directories)
{
entitiesDictionary.Add(directory, directory.Replace(topDirectory, ""));
} string[] files = Directory.GetFiles(source, "*.*", SearchOption.AllDirectories);
foreach (string file in files)
{
entitiesDictionary.Add(file, file.Replace(topDirectory, ""));
}
} return entitiesDictionary;
}
除了支持文件和文件夹压缩解压,还提供了对字节的压缩解压方法:
/// <summary>
/// 压缩字节数组
/// </summary>
/// <param name="sourceBytes">源字节数组</param>
/// <param name="compressionLevel">压缩等级</param>
/// <param name="password">密码</param>
/// <returns>压缩后的字节数组</returns>
public static byte[] CompressBytes(byte[] sourceBytes, string password = null, int compressionLevel = )
{
byte[] result = new byte[] { }; if (sourceBytes.Length > )
{
try
{
using (MemoryStream tempStream = new MemoryStream())
{
using (MemoryStream readStream = new MemoryStream(sourceBytes))
{
using (ZipOutputStream zipStream = new ZipOutputStream(tempStream))
{
zipStream.Password = password;//设置密码
zipStream.SetLevel(CheckCompressionLevel(compressionLevel));//设置压缩等级 ZipEntry zipEntry = new ZipEntry("ZipBytes");
zipEntry.DateTime = DateTime.Now;
zipEntry.Size = sourceBytes.Length;
zipStream.PutNextEntry(zipEntry);
int readLength = ;
byte[] buffer = new byte[BufferSize]; do
{
readLength = readStream.Read(buffer, , BufferSize);
zipStream.Write(buffer, , readLength);
} while (readLength == BufferSize); readStream.Close();
zipStream.Flush();
zipStream.Finish();
result = tempStream.ToArray();
zipStream.Close();
}
}
}
}
catch (System.Exception ex)
{
throw new Exception("压缩字节数组发生错误", ex);
}
} return result;
} /// <summary>
/// 解压字节数组
/// </summary>
/// <param name="sourceBytes">源字节数组</param>
/// <param name="password">密码</param>
/// <returns>解压后的字节数组</returns>
public static byte[] DecompressBytes(byte[] sourceBytes, string password = null)
{
byte[] result = new byte[] { }; if (sourceBytes.Length > )
{
try
{
using (MemoryStream tempStream = new MemoryStream(sourceBytes))
{
using (MemoryStream writeStream = new MemoryStream())
{
using (ZipInputStream zipStream = new ZipInputStream(tempStream))
{
zipStream.Password = password;
ZipEntry zipEntry = zipStream.GetNextEntry(); if (zipEntry != null)
{
byte[] buffer = new byte[BufferSize];
int readLength = ; do
{
readLength = zipStream.Read(buffer, , BufferSize);
writeStream.Write(buffer, , readLength);
} while (readLength == BufferSize); writeStream.Flush();
result = writeStream.ToArray();
writeStream.Close();
}
zipStream.Close();
}
}
}
}
catch (System.Exception ex)
{
throw new Exception("解压字节数组发生错误", ex);
}
}
return result;
}
为了测试该类,我写了一个WinForm程序,界面如下:

程序源代码下载:http://files.cnblogs.com/files/conexpress/SharpZipTest.zip
C#压缩库SharpZipLib的应用的更多相关文章
- ICSharpCode.SharpZipLib 开源压缩库使用示例
官方网站:http://www.icsharpcode.net/OpenSource/SharpZipLib/Default.aspx 插件描述: ICSharpCode.SharpZipLib.dl ...
- [转]Snappy压缩库安装和使用之一
Snappy压缩库安装和使用之一 原文地址:http://blog.csdn.net/luo6620378xu/article/details/8521223 近日需要在毕业设计中引入一个压缩库,要求 ...
- 3D文件压缩库——Draco简析
3D文件压缩库——Draco简析 今年1月份时,google发布了名为“Draco”的3D图形开源压缩库,下载了其代码来看了下,感觉虽然暂时用不到,但还是有前途的,故简单做下分析. 注:Draco 代 ...
- 【神经网络与深度学习】Google Snappy - 一个高速压缩库
Snappy已经被Google开源,作为一个压缩库,它可以利用单颗Intel Corei7处理器内核处理至少每秒250MB~500MB的数据流. Snappy的前身是Zippy.虽然只是一个数据压缩库 ...
- Intel发布神经网络压缩库Distiller:快速利用前沿算法压缩PyTorch模型——AttributeError: module ‘tensorboard' has no attribute 'lazy'
转载自:CSDN Nine-days 近日,Intel 开源了一个用于神经网络压缩的开源 Python 软件包 Distiller,它可以减少深度神经网络的内存占用.加快推断速度及节省能耗.Dis ...
- 【转载】C# 开源库大全非常好
原文地址:http://m.blog.csdn.net/woddle/article/details/37311877 C#开源大全 商业协作和项目管理平台-TeamLab 网络视频会议软件-VMuk ...
- C#开源
商业协作和项目管理平台-TeamLab 网络视频会议软件-VMukti 驰骋工作流程引擎-ccflow [免费]正则表达式测试工具-Regex-Tester Windows-Phone-7-SDK E ...
- C# 开源项目一
商业协作和项目管理平台-TeamLab 网络视频会议软件-VMukti 驰骋工作流程引擎-ccflow [免费]正则表达式测试工具-Regex-Tester Windows-Phone-7-SDK E ...
- C#开源大全--汇总(转)
商业协作和项目管理平台-TeamLab 网络视频会议软件-VMukti 驰骋工作流程引擎-ccflow [免费]正则表达式测试工具-Regex-Tester Windows-Phone-7-SDK E ...
随机推荐
- 使用功能强大的插件FastReport.Net打印报表实例
我第一次使用FastReport插件做的功能是打印一个十分复杂的excel表格,有几百个字段都需要绑定数据,至少需要4个数据源,而且用到横向.竖向合并单元格. 我不是直接连接数据库,而是使用Regis ...
- jqgrid no url reset
如果发现 jqgrid 在运行中出现次错误,可能是以下原因 $('#@(ViewBag.tabcid + "_grid")').jqGrid('navGrid', '#@(View ...
- Lua模块
在lua中,我们可以直接使用require(“model_name”)来载入别的文件,文件的后缀名是.lua,载入的时候直接执行那个文件了. 比如:my.lua 文件中 print(“hello wo ...
- 影响前端的Chrome浏览器36
新发现,在我开发过的组件中表格组件是采用Table生成的,而在Webkit内核浏览器中,Table的列顺序是倒着生成的,所以在组件中要做兼容. 现在Chrome浏览器版本已经升级到36了.发现Tabl ...
- PHP的流程控制结构
1.break 使用break语句可以将深埋在嵌套循环中的语句退出到指定层数或直接退出到最外层,break是接受一个可选的数字参数来决定跳出几重语句.break可以跳出几重语句.break可以跳出几重 ...
- NorthWind 数据库整体关系
http://blog.csdn.net/bergn/article/details/1502150 今天看到一张非常有用的图,说明有关Northwind数据库整体关系的图,以前一直在用,但是没有一个 ...
- 手机版本高于xcode,xcode的快速升级
iPhone手机更新版本,xcode未更新时,不能真机测试 在xcode show in finder里面添加最新iPhone 版本 重启xcode即可 真机测试
- 一段可以清理NSArray中的空对象的代码(递归)
- (NSArray *)clearAllNullObject{ NSMutableArray *array = [self mutableCopy]; ;i < array.count;i++ ...
- 【Git学习笔记】远程仓库
第一种情景:本地初始化一个Git仓库后,接着又在github上创建了一个Git仓库,现在要让这两个仓库进行远程同步. 1. 关联本地仓库就和远程仓库 $ git remote add origin ...
- 给Source Insight做个外挂系列之六--“TabSiPlus”的其它问题
关于如何做一个Source Insight外挂插件的全过程都已经写完了,这么一点东西拖了一年的时间才写完,足以说明我是一个很懒的人,如果不是很多朋友的关心和督促,恐怕是难以完成了.许多朋友希望顺着本文 ...