SharpZipLib,壓縮解壓專家.NET庫(kù)!
大家好,今天我要和小伙伴們分享一個(gè)特別好用的.NET壓縮解壓庫(kù) - SharpZipLib!在開發(fā)中,我們經(jīng)常需要處理文件的壓縮和解壓操作,比如制作安裝包、備份文件等。SharpZipLib就是一個(gè)完全由C#編寫的開源壓縮庫(kù),支持ZIP、GZIP、BZip2等多種壓縮格式。
1. 快速入門
首先通過NuGet安裝SharpZipLib:
powershell復(fù)制
Install-Package SharpZipLib
2. 文件壓縮實(shí)戰(zhàn)
2.1 創(chuàng)建ZIP文件
來看看如何將一個(gè)文件夾壓縮成ZIP文件:
csharp復(fù)制
using ICSharpCode.SharpZipLib.Zip;
public void CreateZipFile(string folderPath, string zipFilePath)
{
FastZip fastZip = new FastZip();
// 是否包含子文件夾
fastZip.CreateEmptyDirectories = true;
// 密碼保護(hù),不需要?jiǎng)t設(shè)為null
fastZip.Password = "123456";
// 開始?jí)嚎s
fastZip.CreateZip(zipFilePath, folderPath, true, "");
}
2.2 解壓ZIP文件
解壓也很簡(jiǎn)單,看代碼:
csharp復(fù)制
using ICSharpCode.SharpZipLib.Zip;
public void ExtractZipFile(string zipFilePath, string extractPath)
{
FastZip fastZip = new FastZip();
// 設(shè)置密碼(如果有的話)
fastZip.Password = "123456";
// 開始解壓
fastZip.ExtractZip(zipFilePath, extractPath, null);
}
3. GZIP壓縮
有時(shí)我們需要壓縮單個(gè)文件或數(shù)據(jù)流,GZIP是個(gè)不錯(cuò)的選擇:
csharp復(fù)制
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. 實(shí)用小技巧
4.1 進(jìn)度監(jiān)控
想知道壓縮進(jìn)度嗎?試試這個(gè):
csharp復(fù)制
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 內(nèi)存壓縮
有時(shí)我們需要在內(nèi)存中進(jìn)行壓縮:
csharp復(fù)制
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();
}
}
小貼士
- 記得處理壓縮文件時(shí)要使用 using 語(yǔ)句,確保資源正確釋放
- 壓縮大文件時(shí),建議使用緩沖區(qū)讀寫,避免內(nèi)存溢出
- 設(shè)置密碼時(shí),推薦使用強(qiáng)密碼,并妥善保管
- 解壓前最好先檢查目標(biāo)路徑是否有足夠空間
閱讀原文:原文鏈接
該文章在 2025/1/24 9:06:18 編輯過