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 編輯過