C# 本身並無提供ZIP相關的類別,我們可使用 SharpZipLib 這個類別庫來處理壓縮檔,有需要可到 SharpZipLib 官方網站下載:
http://www.icsharpcode.net/OpenSource/SharpZipLib/

 

 

如下的 Method,可以將一個資料夾內所有的檔案壓縮成一 .ZIP 檔:

 

// 傳入參數: 來源路徑, 目的壓縮檔名(.zip), 壓縮比( 0=僅儲存, 9=最高壓縮比 )
public static void Compress(string dir, string zipFileName, int level)
{
    string[] filenames = Directory.GetFiles(dir);
    byte[] buffer = new byte[4096];

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

        // 逐一將資料夾內的檔案抓出來壓縮,並寫入至目的檔(.ZIP)
        foreach (string filename in filenames)
        {
            ZipEntry entry = new ZipEntry(filename);
            s.PutNextEntry(entry);

            using (FileStream fs = File.OpenRead(filename))
                StreamUtils.Copy(fs, s, buffer);
        }
    }
}

 

呼叫 Compress ,將 C:\851_ICSharpCode.SharpZipLib_20 資料夾下所有的檔案壓縮成 test.zip,壓縮比 5

Compress("C:\\0851_ICSharpCode.SharpZipLib_20", "C:\\Downloads\\test.zip", 5);

 

 

然後使用如下的方法,可以列舉壓縮檔內所有的檔案:

 

// 傳入參數: 來源壓縮檔檔名
public static void List(string zipFile)
{
    if (File.Exists(zipFile))
    {
        ZipFile zip = new ZipFile(zipFile);

        foreach (ZipEntry entry in zip)
        {
            if (entry.IsFile)
            Console.WriteLine(entry.Name);
        }
    }
    else
        Console.WriteLine(zipFile + " 不存在");
}

 

呼叫 List ,將 test.zip 這壓縮檔所包含的檔案印出:

List("C:\\Downloads\\test.zip");

 


 

解壓縮:

// 解壓縮檔案,傳入參數: 來源壓縮檔, 解壓縮後的目的路徑
public static void Uncompress(string zipFileName, string targetPath)
{
    using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFileName)))
    {
        // 若目的路徑不存在,則先建立路徑
        DirectoryInfo di = new DirectoryInfo(targetPath);

        
if
 (!di.Exists)
            di.Create();

        ZipEntry theEntry;

        // 逐一取出壓縮檔內的檔案(解壓縮)
        while ((theEntry = s.GetNextEntry()) != null)
        {
            int size = 2048;
            byte[] data = new byte[2048];

            Console.WriteLine("正在解壓縮: " + GetBasename(theEntry.Name));

            // 寫入檔案
            using (FileStream fs = new FileStream(di.FullName + "\\" + GetBasename(theEntry.Name), FileMode.Create))
            {
                while (true)
                {
                    size = s.Read(data, 0, data.Length);

                    
if
 (size > 0)
                        fs.Write(data, 0, size);
                    else
                        break;
                }

            }
        }
    }
}

// 取得檔名(去除路徑)
public static string GetBasename(string fullName)
{
    string result;
    int lastBackSlash = fullName.LastIndexOf("\\");
    result = fullName.Substring(lastBackSlash + 1);"

    return result;
}

 

呼叫 Upcompress ,將 test.zip 這壓縮檔解壓縮至 C:\Downloads\test 目錄下:

Uncompress("C:\\Downloads\\test.zip", "C:\\Downloads\\test");

 


若需要更多資訊,可參考 SharpZipLib 官方說明文件。

 

 

arrow
arrow
    全站熱搜

    狼翔月影 發表在 痞客邦 留言(1) 人氣()