C# 將檔案壓縮為 zip 示範

將 image1.jpg 和 image2.jpg 壓縮,放入新建立的 test.zip 壓縮檔中:
    
var filePath1 = @"C:\Users\ruyut\Downloads\image1.jpg";
var filePath2 = @"C:\Users\ruyut\Downloads\image2.jpg";

var zipOutputFilePath = @"C:\Users\ruyut\Downloads\test.zip";

using (var zip = new ZipArchive(File.Open(zipOutputFilePath, FileMode.Create), ZipArchiveMode.Create))
{
    zip.CreateEntryFromFile(filePath1, Path.GetFileName(filePath1));
    zip.CreateEntryFromFile(filePath2, Path.GetFileName(filePath2));
}
    

將 test 資料夾內的檔案壓縮,放入至新建立的 test.zip 壓縮檔中。會遞迴處理資料夾內的資料夾和檔案:
    
var folderPath = @"C:\Users\ruyut\Downloads\test";
var zipOutputFilePath = @"C:\Users\ruyut\Downloads\test.zip";

using (var zip = new ZipArchive(File.Open(zipOutputFilePath, FileMode.Create), ZipArchiveMode.Create))
{
    foreach (var file in Directory.EnumerateFiles(folderPath, "*", SearchOption.AllDirectories))
    {
        zip.CreateEntryFromFile(file, file.Replace(folderPath, "").TrimStart('\\'));
    }
}

    



參考資料:
Microsoft.Learn - ZipArchive Class
Microsoft.Learn - ZipArchive Constructors

留言