【C#】SharpZipLib,压缩解压专家.NET库!
|
admin
2025年1月23日 22:53
本文热度 366
|
SharpZipLib,压缩解压专家.NET库!
大家好,今天我要和小伙伴们分享一个特别好用的.NET压缩解压库 - SharpZipLib!在开发中,我们经常需要处理文件的压缩和解压操作,比如制作安装包、备份文件等。SharpZipLib就是一个完全由C#编写的开源压缩库,支持ZIP、GZIP、BZip2等多种压缩格式。
1. 快速入门
首先通过NuGet安装SharpZipLib:
powershell复制
Install-Package SharpZipLib
2. 文件压缩实战
2.1 创建ZIP文件
来看看如何将一个文件夹压缩成ZIP文件:
csharp复制
using ICSharpCode.SharpZipLib.Zip;
public void CreateZipFile(string folderPath, string zipFilePath)
{
FastZip fastZip = new FastZip();
// 是否包含子文件夹
fastZip.CreateEmptyDirectories = true;
// 密码保护,不需要则设为null
fastZip.Password = "123456";
// 开始压缩
fastZip.CreateZip(zipFilePath, folderPath, true, "");
}
2.2 解压ZIP文件
解压也很简单,看代码:
csharp复制
using ICSharpCode.SharpZipLib.Zip;
public void ExtractZipFile(string zipFilePath, string extractPath)
{
FastZip fastZip = new FastZip();
// 设置密码(如果有的话)
fastZip.Password = "123456";
// 开始解压
fastZip.ExtractZip(zipFilePath, extractPath, null);
}
3. GZIP压缩
有时我们需要压缩单个文件或数据流,GZIP是个不错的选择:
csharp复制
using ICSharpCode.SharpZipLib.GZip;
public void CompressWithGZip(string sourceFile, string compressedFile)
{
using (FileStream sourceStream = File.OpenRead(sourceFile))
using (FileStream targetStream = File.Create(compressedFile))
using (GZipOutputStream gzipStream = new GZipOutputStream(targetStream))
{
byte[] buffer = new byte[4096];
int readCount;
while ((readCount = sourceStream.Read(buffer, 0, buffer.Length)) >; 0)
{
gzipStream.Write(buffer, 0, readCount);
}
}
}
4. 实用小技巧
4.1 进度监控
想知道压缩进度吗?试试这个:
csharp复制
public void ZipWithProgress(string folderPath, string zipFilePath, Action<;int>; progressCallback)
{
FastZip fastZip = new FastZip();
fastZip.CreateZip(zipFilePath, folderPath, true, "");
long totalSize = new DirectoryInfo(folderPath)
.GetFiles("*.*", SearchOption.AllDirectories)
.Sum(file =>; file.Length);
using (FileStream fs = File.OpenRead(zipFilePath))
{
int progress = (int)((fs.Length * 100) / totalSize);
progressCallback(progress);
}
}
4.2 内存压缩
有时我们需要在内存中进行压缩:
csharp复制
public byte[] CompressInMemory(byte[] data)
{
using (MemoryStream msCompressed = new MemoryStream())
{
using (GZipOutputStream gzipStream = new GZipOutputStream(msCompressed))
{
gzipStream.Write(data, 0, data.Length);
}
return msCompressed.ToArray();
}
}
小贴士
- 记得处理压缩文件时要使用 using 语句,确保资源正确释放
阅读原文:原文链接
该文章在 2025/1/24 9:06:18 编辑过