[C#][.NETCore] 壓縮檔案 & 解壓縮檔案

在 .NET Framework 的時候有好用的 DotNetZip 可以快速壓縮&解壓縮檔案
但在寫 .NET Core 的時候發現這個套件不能使用,那只好默默地自己寫了

這邊就用 System.IO.Compression 提供的 ZipArchive 來簡單寫個壓縮 & 解壓縮範例

壓縮檔案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
string rootPath = AppDomain.CurrentDomain.BaseDirectory;
string saveFileName = Path.Combine(rootPath, "test.zip");
string zipFileName = Path.Combine(rootPath, "123.txt");

using (var fs = new FileStream(saveFileName, FileMode.OpenOrCreate))
{
using (ZipArchive zipArchive = new ZipArchive(fs, ZipArchiveMode.Create))
{
string fileName = Path.GetFileName(zipFileName);

var zipArchiveEntry = zipArchive.CreateEntry(fileName);
using (var zipStream = zipArchiveEntry.Open())
{
byte[] bytes = File.ReadAllBytes(zipFileName);
zipStream.Write(bytes, 0, bytes.Length);
}
}
}

解壓縮檔案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
string rootPath = AppDomain.CurrentDomain.BaseDirectory;
string zipFileName = Path.Combine(rootPath, "test.zip");
string saveFolder = rootPath;

using (var fs = new FileStream(zipFileName, FileMode.Open))
{
using (ZipArchive zipArchive = new ZipArchive(fs, ZipArchiveMode.Read))
{
foreach (ZipArchiveEntry zipArchiveEntry in zipArchive.Entries)
{
string temp = Path.Combine(saveFolder, zipArchiveEntry.FullName);
zipArchiveEntry.ExtractToFile(temp);
}
}
}

解壓縮的時候最好可以將 zipArchiveEntry.FullName 再做一層處理,避免產生資安問題 (詳情)