ZIP壓縮處理 ZIP壓縮處理
  .NET       ez      2011-11-28

SharpZipLib 官方網站下載:http://www.icsharpcode.net/OpenSource/SharpZipLib/ or SharpZipLib 0.86 壓縮檔案

Compress("C:\\ziproute", "C:\\ziproute.zip", 5);
// 傳入參數: 來源路徑, 目的壓縮檔名(.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);
        }
    }
}

解壓縮檔案

Uncompress("C:\\ziproute.zip", "C:\\ziproute");

// 解壓縮檔案,傳入參數: 來源壓縮檔, 解壓縮後的目的路徑
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;
}

列舉壓縮檔內所有的檔案

List("C:\\ziproute.zip");
// 傳入參數: 來源壓縮檔檔名
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 + " 不存在");
}

ZipTool

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

namespace ZipTool
{
    public class ZipTool
    {
        /// <summary>
        /// 壓縮整個資料夾
        /// </summary>
        private static void ZipDir(string SourceDir, string TargetFile, string Password, bool BackupOldFile)
        {
            FastZip oZipDir = new FastZip();
            try
            {
                if (!Directory.Exists(SourceDir))
                {
                    throw new Exception("資料夾不存在!");
                }

                if (BackupOldFile == true)
                {
                    //判斷要產生的ZIP檔案是否存在
                    if (File.Exists(TargetFile) == true)
                    {
                        //原本的檔案存在,把他ReName
                        File.Copy(TargetFile, TargetFile + "-" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".back");
                        File.Delete(TargetFile);
                    }
                }

                if (string.IsNullOrEmpty(Password))
                    oZipDir.Password = Password;

                oZipDir.CreateZip(TargetFile, SourceDir, true, "");
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 壓縮整個資料夾
        /// </summary>
        public static void ZipDir(string SourceDir, string TargetFile, string Password)
        {
            ZipDir(SourceDir, TargetFile, Password, true);
        }

        /// <summary>
        /// 壓縮整個資料夾
        /// </summary>
        public static void ZipDir(string SourceDir, string TargetFile)
        {
            ZipDir(SourceDir, TargetFile, "", true);
        }

        /// <summary>
        /// 壓縮檔案
        /// </summary>
        private static void ZipFiles(string[] SourceFiles, string TargetFile, string Password, bool BackupOldFile)
        {
            try
            {
                if (SourceFiles == null || SourceFiles.Length <= 0)
                {
                    throw new Exception("並未傳入檔案完整路徑");
                }

                for (int i = 0; i < SourceFiles.Length; i++)
                {
                    if (File.Exists(SourceFiles[i]) == false)
                    {
                        throw new Exception("要壓縮的檔案【" + SourceFiles[i] + "】不存在");
                    }
                }

                if (BackupOldFile == true)
                {
                    //判斷要產生的ZIP檔案是否存在
                    if (File.Exists(TargetFile) == true)
                    {
                        //原本的檔案存在,把他ReName
                        File.Copy(TargetFile, TargetFile + "-" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".back");
                        File.Delete(TargetFile);
                    }
                }

                ZipOutputStream zs = new ZipOutputStream(File.Create(TargetFile));
                zs.SetLevel(9); //壓縮比
                if (Password != "")
                {
                    zs.Password = Password;
                }

                for (int i = 0; i < SourceFiles.Length; i++)
                {
                    FileStream s = File.OpenRead(SourceFiles[i]);
                    byte[] buffer = new byte[s.Length];
                    s.Read(buffer, 0, buffer.Length);
                    ZipEntry Entry = new ZipEntry(Path.GetFileName(SourceFiles[i]));
                    Entry.DateTime = DateTime.Now;
                    Entry.Size = s.Length;
                    s.Close();
                    zs.PutNextEntry(Entry);
                    zs.Write(buffer, 0, buffer.Length);
                }
                zs.Finish();
                zs.Close();
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 壓縮檔案
        /// </summary>
        public static void ZipFiles(string[] SourceFiles, string TargetFile, string Password)
        {
            ZipFiles(SourceFiles, TargetFile, Password, true);
        }

        /// <summary>
        /// 壓縮檔案
        /// </summary>
        public static void ZipFiles(string[] SourceFiles, string TargetFile)
        {
            ZipFiles(SourceFiles, TargetFile, "", true);
        }

        /// <summary>
        /// 壓縮單一檔案
        /// </summary>
        public static void ZipFile(string SourceFile, string TargetFile, string Password, bool BackupOldFile)
        {
            ZipFiles(new string[] { SourceFile }, TargetFile, Password, BackupOldFile);
        }

        /// <summary>
        /// 壓縮單一檔案
        /// </summary>
        public static void ZipFile(string SourceFile, string TargetFile, string Password)
        {
            ZipFile(SourceFile, TargetFile, Password, true);
        }

        /// <summary>
        /// 壓縮單一檔案
        /// </summary>
        /// <returns>
        public static void ZipFile(string SourceFile, string TargetFile)
        {
            ZipFile(SourceFile, TargetFile, "", true);
        }

        /// <summary>
        /// 解壓縮
        /// </summary>
        private static void ExtractZip(string SourceFile, string TargetDir, string Password)
        {
            FastZip oZip = new FastZip();
            try
            {
                //判斷ZIP檔案是否存在
                if (File.Exists(SourceFile) == false)
                {
                    throw new Exception("要解壓縮的檔案【" + SourceFile + "】不存在,無法執行");
                }
                if (Password != "")
                {
                    oZip.Password = Password;
                }
                oZip.ExtractZip(SourceFile, TargetDir, "");
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 解壓縮
        /// </summary>
        public static void ExtractZip(string SourceFile, string TargetDir)
        {
            ExtractZip(SourceFile, TargetDir, "");
        }
    }
}

標籤:   .NET

我要留言