# [C#]壓縮檔 (使用第三方套建 Ionic.Zip)
###### tags: `c#` `Zip` `Ionic.Zip` `Visual Studio`
> [time= 2019 11 06 ] 
<br>
## 在 Visual Studio 安裝 Ionic.Zip
在專案點右鍵 > 選「管理NuGet」

<br><br><br>
搜尋「Ionic.Zip」> 點Ionic.Zip > 安裝

<br><br><br>
新增 class 名為 `ZipUtilities`,實作 **壓縮** 和 **解壓縮** 功能:
```csharp=
using Ionic.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ConsoleIonicZip
{
    class ZipUtilities
    {
        // 壓縮   
        public bool FileZip(List<string> fileList, string targetPath, string targetFileName, string filePassword)
        {
            try
            {
                // 若不指定目的與目的檔名則取第一個 List 當作目的檔名
                if (!string.IsNullOrEmpty(fileList.FirstOrDefault()) && string.IsNullOrEmpty(targetPath))
                {
                    targetPath = Path.GetDirectoryName(fileList.FirstOrDefault());
                    targetFileName = Path.GetFileNameWithoutExtension(fileList.FirstOrDefault());
                }
                using (ZipFile dotZip = new ZipFile())
                {
                    if (!string.IsNullOrEmpty(filePassword))
                        dotZip.Password = filePassword;
                    foreach (var item in fileList)
                    {
                        if (File.Exists(item.ToString()))
                            dotZip.AddFile(item.ToString(), "");
                    }
                    dotZip.Save(string.Format(@"{0}.zip", Path.Combine(targetPath, targetFileName)));
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        // 解壓縮
        public bool fileUnZip(string filePath, string targetPath, string filePassword)
        {
            using (Ionic.Zip.ZipFile DotZip = Ionic.Zip.ZipFile.Read(filePath))
            {
                if (!string.IsNullOrEmpty(filePassword))
                    DotZip.Password = filePassword;
                DotZip.ExtractAll(targetPath, ExtractExistingFileAction.OverwriteSilently);  // 解壓縮路徑  
                var result = DotZip.EntryFileNames.ToList();
            }
            return true;
        }
    }
}
```
<br><br><br>
在主程式使用 zip 功能
```csharp=
using System.Collections.Generic;
namespace ConsoleIonicZip
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> fileList = new List<string>();
            fileList.Add("your files");
            string zipTargetPath = "your target path";
            string zipTargetFileName = "your target file name";
            string zipPassword = "yor Zip password";
            string localPath = "your local path";
            var zip = new ZipUtilities();
            // 檔案壓縮
            var zipResult = zip.FileZip(fileList, zipTargetPath, zipTargetFileName, zipPassword);
            // 檔案解壓縮
            zipResult = zip.fileUnZip(localPath, zipTargetPath, zipPassword);
        }
    }
}
```