Sunday, April 19, 2009

在 C# 下將檔案壓成 ZIP 檔

前陣子手上有個案子需要將產出的檔案壓成ZIP再用FTPS送出,問過Google大神後,決定使用SharpZipLib來處理壓成ZIP這個工作。

SharpZipLib下載
範例與程式碼下載
說明文件下載

SharpZipLib下載後,有三個資料夾([net-11],[net-20],[netcf-20]),我是用VS2005開發,所以就把[net-20]裡的ICSharpCode.SharpZipLib.dll找個地方放好,然後加入參考,這樣就可以用了(不用註冊元件)。

因為我的需求很單純,只要把指定檔案壓縮成指定檔名,所以只用了下面這個壓縮功能,如果要更多的功能可以看範例或是問Google大神,有很多人分享了。 (後面我也會列一些)


程式開頭記得加using
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Core;

/// 壓縮檔案
// 傳入參數: 來源檔名, 目的檔名, 壓縮比( 無0~9最高 )
public static void Compress(string fileName, string zipFileName, int level)
{
byte[] buffer = new byte[4096];

using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFileName)))
{
// 設定壓縮比
s.SetLevel(level);

ZipEntry entry = new ZipEntry(fileName);
s.PutNextEntry(entry);

using (FileStream fs = File.OpenRead(fileName))
StreamUtils.Copy(fs, s, buffer);
}
Console.WriteLine("Compress to " + zipFileName + " done");
}

用的時候直接Compress("test.txt","text.zip",9); 就可以了,要壓成不同檔名自己改就好。


參考資源:

.Net Library #ziplib (SharpZipLib)
C# 處理 ZIP 壓縮檔
C#, SharpZip 應用
C# 在線解壓Zip檔

1 comment:

  1. 補一下,如果因為解壓軟體太舊不能解用SharpZipLib壓出來的檔的話,加入s.UseZip64 = UseZip64.Off;這行就好了

    ReplyDelete