C# ZipHelper C#公共类 压缩和解压
关于本文档的说明
本文档基于ICSharpCode.SharpZipLib.dll的封装,常用的解压和压缩方法都已经涵盖在内,都是经过项目实战积累下来的
1.基本介绍
由于项目中需要用到各种压缩将文件进行压缩下载,减少网络的带宽,所以压缩是一个非常常见的功能,对于压缩微软自己也提供了一些类库
- 微软自带压缩类ZipArchive类,适合NET FrameWork4.5才可以使用
- 调用压缩软件命令执行压缩动作,这个就需要电脑本身安装压缩软件了
- 使用第三方的压缩dll文件,一般使用最多的是(ICSharpCode.SharpZipLib.dll),下载dll ICSharpCode.SharpZipLib.zip
2.实际项目
- 压缩单个文件,需要指定压缩等级
- 压缩单个文件夹,需要指定压缩等级
- 压缩多个文件或者多个文件夹
- 对压缩包进行加密【用的较少,实际情况也有】
- 直接解压,无需密码
- 需要密码解压
2.1 压缩单个文件

2.2 压缩单个文件夹
public void ZipDir(string dirToZip, string zipedFileName, int compressionLevel = )
2.3 压缩多个文件或者文件夹
public bool ZipManyFilesOrDictorys(IEnumerable<string> folderOrFileList, string zipedFile, string password)
2.4 对压缩包进行加密
public bool ZipManyFilesOrDictorys(IEnumerable<string> folderOrFileList, string zipedFile, string password)
2.5 直接解压,无需密码
public void UnZip(string zipFilePath, string unZipDir)
3.演示图
3.ZipHelper下载
//-------------------------------------------------------------------------------------
// All Rights Reserved , Copyright (C) 2016 , ZTO , Ltd .
//------------------------------------------------------------------------------------- using System;
using System.Collections;
using System.Collections.Generic;
using System.IO; namespace ZTO.PicTest.Utilities
{
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip; /// <summary>
/// Zip压缩帮助类
///
/// 修改纪录
///
/// 2015-09-16 版本:1.0 YangHengLian 创建主键,注意命名空间的排序。
/// 2016-5-7 YangHengLian增加了可以支持多个文件或者多个文件夹打包成一个zip文件
///
/// 版本:1.0
///
/// <author>
/// <name>YangHengLian</name>
/// <date>2015-09-16</date>
/// </author>
/// </summary>
public class ZipHelper
{
/// <summary>
/// 压缩文件夹
/// </summary>
/// <param name="dirToZip"></param>
/// <param name="zipedFileName"></param>
/// <param name="compressionLevel">压缩率0(无压缩)9(压缩率最高)</param>
public void ZipDir(string dirToZip, string zipedFileName, int compressionLevel = )
{
if (Path.GetExtension(zipedFileName) != ".zip")
{
zipedFileName = zipedFileName + ".zip";
}
using (var zipoutputstream = new ZipOutputStream(File.Create(zipedFileName)))
{
zipoutputstream.SetLevel(compressionLevel);
Crc32 crc = new Crc32();
Hashtable fileList = GetAllFies(dirToZip);
foreach (DictionaryEntry item in fileList)
{
FileStream fs = new FileStream(item.Key.ToString(), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, , buffer.Length);
// ZipEntry entry = new ZipEntry(item.Key.ToString().Substring(dirToZip.Length + 1));
ZipEntry entry = new ZipEntry(Path.GetFileName(item.Key.ToString()))
{
DateTime = (DateTime) item.Value,
Size = fs.Length
};
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
zipoutputstream.PutNextEntry(entry);
zipoutputstream.Write(buffer, , buffer.Length);
}
}
} /// <summary>
/// 获取所有文件
/// </summary>
/// <returns></returns>
public Hashtable GetAllFies(string dir)
{
Hashtable filesList = new Hashtable();
DirectoryInfo fileDire = new DirectoryInfo(dir);
if (!fileDire.Exists)
{
throw new FileNotFoundException("目录:" + fileDire.FullName + "没有找到!");
} GetAllDirFiles(fileDire, filesList);
GetAllDirsFiles(fileDire.GetDirectories(), filesList);
return filesList;
} /// <summary>
/// 获取一个文件夹下的所有文件夹里的文件
/// </summary>
/// <param name="dirs"></param>
/// <param name="filesList"></param>
public void GetAllDirsFiles(IEnumerable<DirectoryInfo> dirs, Hashtable filesList)
{
foreach (DirectoryInfo dir in dirs)
{
foreach (FileInfo file in dir.GetFiles("*.*"))
{
filesList.Add(file.FullName, file.LastWriteTime);
}
GetAllDirsFiles(dir.GetDirectories(), filesList);
}
} /// <summary>
/// 获取一个文件夹下的文件
/// </summary>
/// <param name="dir">目录名称</param>
/// <param name="filesList">文件列表HastTable</param>
public static void GetAllDirFiles(DirectoryInfo dir, Hashtable filesList)
{
foreach (FileInfo file in dir.GetFiles("*.*"))
{
filesList.Add(file.FullName, file.LastWriteTime);
}
} /// <summary>
/// 功能:解压zip格式的文件。
/// </summary>
/// <param name="zipFilePath">压缩文件路径</param>
/// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param>
/// <returns>解压是否成功</returns>
public void UnZip(string zipFilePath, string unZipDir)
{
if (zipFilePath == string.Empty)
{
throw new Exception("压缩文件不能为空!");
}
if (!File.Exists(zipFilePath))
{
throw new FileNotFoundException("压缩文件不存在!");
}
//解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
if (unZipDir == string.Empty)
unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));
if (!unZipDir.EndsWith("/"))
unZipDir += "/";
if (!Directory.Exists(unZipDir))
Directory.CreateDirectory(unZipDir); using (var s = new ZipInputStream(File.OpenRead(zipFilePath)))
{ ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
if (!string.IsNullOrEmpty(directoryName))
{
Directory.CreateDirectory(unZipDir + directoryName);
}
if (directoryName != null && !directoryName.EndsWith("/"))
{
}
if (fileName != String.Empty)
{
using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))
{ int size;
byte[] data = new byte[];
while (true)
{
size = s.Read(data, , data.Length);
if (size > )
{
streamWriter.Write(data, , size);
}
else
{
break;
}
}
}
}
}
}
} /// <summary>
/// 压缩单个文件
/// </summary>
/// <param name="filePath">被压缩的文件名称(包含文件路径),文件的全路径</param>
/// <param name="zipedFileName">压缩后的文件名称(包含文件路径),保存的文件名称</param>
/// <param name="compressionLevel">压缩率0(无压缩)到 9(压缩率最高)</param>
public void ZipFile(string filePath, string zipedFileName, int compressionLevel = )
{
// 如果文件没有找到,则报错
if (!File.Exists(filePath))
{
throw new FileNotFoundException("文件:" + filePath + "没有找到!");
}
// 如果压缩后名字为空就默认使用源文件名称作为压缩文件名称
if (string.IsNullOrEmpty(zipedFileName))
{
string oldValue = Path.GetFileName(filePath);
if (oldValue != null)
{
zipedFileName = filePath.Replace(oldValue, "") + Path.GetFileNameWithoutExtension(filePath) + ".zip";
}
}
// 如果压缩后的文件名称后缀名不是zip,就是加上zip,防止是一个乱码文件
if (Path.GetExtension(zipedFileName) != ".zip")
{
zipedFileName = zipedFileName + ".zip";
}
// 如果指定位置目录不存在,创建该目录 C:\Users\yhl\Desktop\大汉三通
string zipedDir = zipedFileName.Substring(, zipedFileName.LastIndexOf("\\", StringComparison.Ordinal));
if (!Directory.Exists(zipedDir))
{
Directory.CreateDirectory(zipedDir);
}
// 被压缩文件名称
string filename = filePath.Substring(filePath.LastIndexOf("\\", StringComparison.Ordinal) + );
var streamToZip = new FileStream(filePath, FileMode.Open, FileAccess.Read);
var zipFile = File.Create(zipedFileName);
var zipStream = new ZipOutputStream(zipFile);
var zipEntry = new ZipEntry(filename);
zipStream.PutNextEntry(zipEntry);
zipStream.SetLevel(compressionLevel);
var buffer = new byte[];
Int32 size = streamToZip.Read(buffer, , buffer.Length);
zipStream.Write(buffer, , size);
try
{
while (size < streamToZip.Length)
{
int sizeRead = streamToZip.Read(buffer, , buffer.Length);
zipStream.Write(buffer, , sizeRead);
size += sizeRead;
}
}
finally
{
zipStream.Finish();
zipStream.Close();
streamToZip.Close();
}
} /// <summary>
/// 压缩单个文件
/// </summary>
/// <param name="fileToZip">要进行压缩的文件名,全路径</param>
/// <param name="zipedFile">压缩后生成的压缩文件名,全路径</param>
public void ZipFile(string fileToZip, string zipedFile)
{
// 如果文件没有找到,则报错
if (!File.Exists(fileToZip))
{
throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");
}
using (FileStream fileStream = File.OpenRead(fileToZip))
{
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, , buffer.Length);
fileStream.Close();
using (FileStream zipFile = File.Create(zipedFile))
{
using (ZipOutputStream zipOutputStream = new ZipOutputStream(zipFile))
{
// string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\") + 1);
string fileName = Path.GetFileName(fileToZip);
var zipEntry = new ZipEntry(fileName)
{
DateTime = DateTime.Now,
IsUnicodeText = true
};
zipOutputStream.PutNextEntry(zipEntry);
zipOutputStream.SetLevel();
zipOutputStream.Write(buffer, , buffer.Length);
zipOutputStream.Finish();
zipOutputStream.Close();
}
}
}
} /// <summary>
/// 压缩多个目录或文件
/// </summary>
/// <param name="folderOrFileList">待压缩的文件夹或者文件,全路径格式,是一个集合</param>
/// <param name="zipedFile">压缩后的文件名,全路径格式</param>
/// <param name="password">压宿密码</param>
/// <returns></returns>
public bool ZipManyFilesOrDictorys(IEnumerable<string> folderOrFileList, string zipedFile, string password)
{
bool res = true;
using (var s = new ZipOutputStream(File.Create(zipedFile)))
{
s.SetLevel();
if (!string.IsNullOrEmpty(password))
{
s.Password = password;
}
foreach (string fileOrDir in folderOrFileList)
{
//是文件夹
if (Directory.Exists(fileOrDir))
{
res = ZipFileDictory(fileOrDir, s, "");
}
else
{
//文件
res = ZipFileWithStream(fileOrDir, s);
}
}
s.Finish();
s.Close();
return res;
}
} /// <summary>
/// 带压缩流压缩单个文件
/// </summary>
/// <param name="fileToZip">要进行压缩的文件名</param>
/// <param name="zipStream"></param>
/// <returns></returns>
private bool ZipFileWithStream(string fileToZip, ZipOutputStream zipStream)
{
//如果文件没有找到,则报错
if (!File.Exists(fileToZip))
{
throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");
}
//FileStream fs = null;
FileStream zipFile = 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();
zipEntry = new ZipEntry(Path.GetFileName(fileToZip));
zipStream.PutNextEntry(zipEntry);
zipStream.Write(buffer, , buffer.Length);
}
catch
{
res = false;
}
finally
{
if (zipEntry != null)
{
} if (zipFile != null)
{
zipFile.Close();
}
GC.Collect();
GC.Collect();
}
return res; } /// <summary>
/// 递归压缩文件夹方法
/// </summary>
/// <param name="folderToZip"></param>
/// <param name="s"></param>
/// <param name="parentFolderName"></param>
private bool ZipFileDictory(string folderToZip, ZipOutputStream s, string parentFolderName)
{
bool res = true;
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();
//先压缩文件,再递归压缩文件夹
var 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();
}
if (entry != null)
{
}
GC.Collect();
GC.Collect();
}
var folders = Directory.GetDirectories(folderToZip);
foreach (string folder in folders)
{
if (!ZipFileDictory(folder, s, Path.Combine(parentFolderName, Path.GetFileName(folderToZip))))
{
return false;
}
}
return res;
}
}
}
ZipHelper
C# ZipHelper C#公共类 压缩和解压的更多相关文章
- .net文件压缩和解压及中文文件夹名称乱码问题
/**************************注释区域内为引用http://www.cnblogs.com/zhaozhan/archive/2012/05/28/2520701.html的博 ...
- .NET中zip的压缩和解压
在.NET可以通过多种方式实现zip的压缩和解压:1.使用System.IO.Packaging:2.使用第三方类库:3.通过 System.IO.Compression 命名空间中新增的ZipArc ...
- ZipHelper 压缩和解压帮助类
ZipHelper 压缩和解压帮助类 关于本文档的说明 本文档基于ICSharpCode.SharpZipLib.dll的封装,常用的解压和压缩方法都已经涵盖在内,都是经过项目实战积累下来的 欢迎传播 ...
- 【C#公共帮助类】WinRarHelper帮助类,实现文件或文件夹压缩和解压,实战干货
关于本文档的说明 本文档使用WinRAR方式来进行简单的压缩和解压动作,纯干货,实际项目这种压缩方式用的少一点,一般我会使用第三方的压缩dll来实现,就如同我上一个压缩类博客,压缩的是zip文件htt ...
- c#自带压缩类实现的多文件压缩和解压
用c#自带的System.IO.Compression命名空间下的压缩类实现的多文件压缩和解压功能,缺点是多文件压缩包的解压只能调用自身的解压方法,和现有的压缩软件不兼容.下面的代码没有把多文件的目录 ...
- 利用c#自带的类对文件进行压缩和解压处理
在做网络传输文件的小例子的时候,当传输的文件比较大的时候,我们通常都是将文件经过压缩之后才进行传输,以前都是利用第三方插件来对文件进行压缩的,但是现在我发现了c#自带的类库也能够实现文件的压缩,实际上 ...
- Linux 时间日期类、搜索查找类、 压缩和解压类指令
l 时间日期类 date指令-显示当前日期 基本语法 1) date (功能描述:显示当前时间) 2) date +%Y (功能描述:显示当前年份) 3) date +%m (功能描述:显示当前月份) ...
- Linux时间日期类,压缩和解压类
一.时间日期类 1.data指令 1.基本指令 date 显示当前日期 data +%Y 显示当前年份 data +%m 显示当前月份 data +%d 显示当前天 data +%Y-%m-%d %H ...
- 【转】Java压缩和解压文件工具类ZipUtil
特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...
随机推荐
- linux 安装apahce的configure: error: APR not found. Please read the documentation解决办法
1.下载所需软件包: 下载apr并配置 wget http://apache.freelamp.com/apr/apr-1.4.2.tar.gz 下载apr ./configure –prefix=/ ...
- Android Service Intent must be explicit的解决方法
今天在学习Android的Service组件的时候,在AndroidMainfest.xml中定义了 <service android:name=".BindService" ...
- 30天,O2O速成攻略【7.25北京站】
活动概况 时间:2015年7月25日13:30-16:30 地点:车库咖啡(北京市海淀西大街48号鑫鼎宾馆二层) 主办:APICloud.领通科技.快易行 网址:www.apicloud.com 费用 ...
- javascript设计模式学习之十二——享元模式
一.享元模式的定义及使用场景 享元模式是为了解决性能问题而诞生的设计模式,这和大部分设计模式为了提高程序复用性的原因不太一样,如果系统中因为创建了大量类似对象而导致内存占用过高,享元模式就非常有用了. ...
- python MySQLdb中文乱码
Python操作MySQL需要安装Python-MySQL可以从网上搜索一下,和一般的Python包一样安装 安装好之后,模块名字叫做MySQLdb ,在Window和Linux环境下都可以使用,试验 ...
- mysql-proxy之奇虎360 Atlas 安装实现mysql读写分离
官方git https://github.com/Qihoo360/Atlas 参照:http://blog.qixingzhong.com/2013/09/centos-install-atlas. ...
- 使用NBU进行oracle异机恢复
windows平台的异机恢复,目录不同 1.异机环境准备安装oracle介质安装nbu客户端在异机主机的host文件中添加nbu server主机和原主机信息 2.恢复spfile文件 C:\> ...
- MongoDB(一):安装
安装 从度娘上搜索MongoDB,找到官网地址:https://www.mongodb.com 找到下载中心地址:https://www.mongodb.com/download-center 我下载 ...
- sql server常见服务
根据您决定安装的组件,SQL Server 安装程序将安装以下服务: SQL Server Database Services - 用于 SQL Server 关系数据库引擎的服务. 可执行文件为 & ...
- Swift实战-豆瓣电台(五)播放音乐
观看地址 http://v.youku.com/v_show/id_XNzMwODM0MzI0.html 在这节里面,我们简单学习了一下MediaPlayer的使用 引入媒体框架 import Med ...