專案開發常需處理檔案壓縮與解壓縮。SharpZipLib 是 .NET 生態系中知名的開源壓縮庫。本文將詳細說明如何利用 SharpZipLib 建立 ZipClass 與 UnZipClass 兩個實用類別,涵蓋單檔壓縮、多檔打包、壓縮等級設定等核心功能,助您快速上手。
ICSharpCode.SharpZipLib.dll 並加入專案參考。ICSharpCode.SharpZipLib.Zip、ICSharpCode.SharpZipLib.Checksums、ICSharpCode.SharpZipLib.GZip、System.IO。using System;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
namespace Compression
{
public class ZipClass
{
/// 壓縮單一檔案
public void ZipFile(string fileToZip, string zippedFile, int compressionLevel, int blockSize)
{
if (!File.Exists(fileToZip))
throw new FileNotFoundException($"找不到指定檔案:{fileToZip}");
using (FileStream streamToZip = File.OpenRead(fileToZip))
using (FileStream zipFile = File.Create(zippedFile))
using (ZipOutputStream zipStream = new ZipOutputStream(zipFile))
{
ZipEntry entry = new ZipEntry("ZippedFile");
zipStream.PutNextEntry(entry);
zipStream.SetLevel(compressionLevel);
byte[] buffer = new byte[blockSize];
int size = streamToZip.Read(buffer, 0, buffer.Length);
zipStream.Write(buffer, 0, size);
while (size < streamToZip.Length)
{
int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);
zipStream.Write(buffer, 0, sizeRead);
size += sizeRead;
}
zipStream.Finish();
}
}
/// 批次壓縮目錄下所有檔案
public void ZipFileMain(string[] args)
{
string[] filenames = Directory.GetFiles(args[0]);
using (ZipOutputStream s = new ZipOutputStream(File.Create(args[1])))
{
s.SetLevel(6);
Crc32 crc = new Crc32();
foreach (string file in filenames)
{
using (FileStream fs = File.OpenRead(file))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
ZipEntry entry = new ZipEntry(file);
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
s.PutNextEntry(entry);
s.Write(buffer, 0, buffer.Length);
}
}
s.Finish();
}
}
}
}
using 區塊自動釋放資源,避免檔案鎖定。blockSize 控制每次讀寫緩衝區大小,影響效能與記憶體佔用。ZipEntry.Name 編碼設定或升級至新版 SharpZipLib。ZipOutputStream.UseZip64 屬性以支援 4GB 以上檔案。透過封裝 ZipClass,即可輕鬆整合檔案壓縮功能至專案中。後續可擴充解壓縮類別 UnZipClass、支援密碼保護、分卷壓縮等進階功能。