c# 檔案壓縮DotNetZip和SharpZipLib

qingjiawen發表於2024-05-28

SharpZipLib 和 DotNetZip

DotNetZip示例

using System;
using System.IO;
using Ionic.Zip;
 
class Program
{
    static void Main(string[] args)
    {
        string folderToCompress = @"C:\path\to\your\folder"; // 要壓縮的資料夾路徑
        string zipFilePath = @"C:\path\to\your\zipfile.zip"; // 壓縮檔案儲存路徑
 
        using (ZipFile zip = new ZipFile(Encoding.Default))//encodeing.default訪止目錄下有中文壓縮後成亂碼
        {
            zip.AddDirectory(folderToCompress, ""); // 新增資料夾到壓縮檔案,第二個引數為壓縮後的資料夾名稱,傳入空字串表示不改變資料夾結構
            zip.Save(zipFilePath); // 儲存壓縮檔案
        }
 
        Console.WriteLine("Folder compressed successfully.");
    }
}

SharpZipLib

using System;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
 
public class ZipHelper
{
    public static void ZipDirectory(string folderName, string zipFileName)
    {
        using (var zipOutputStream = new ZipOutputStream(File.Create(zipFileName)))
        {
            zipOutputStream.SetLevel(6); // 0-9, 9 being the highest level of compression
            ProcessDirectory(zipOutputStream, folderName, string.Empty);
            zipOutputStream.Finish();
            zipOutputStream.Close();
        }
    }
 
    private static void ProcessDirectory(ZipOutputStream zipOutputStream, string path, string subPath)
    {
        var directoryPath = Path.Combine(path, subPath);
 
        // Adds the path to the zip file, just like windows does
        // with the folders, maintaing the directory structure
        zipOutputStream.PutNextEntry(new ZipEntry(Path.GetDirectoryName(directoryPath) + Path.DirectorySeparatorChar));
 
        foreach (var filePath in Directory.GetFiles(directoryPath))
        {
            // Create a zip entry based on the file path
            zipOutputStream.PutNextEntry(new ZipEntry(filePath.Substring(path.Length + 1)));
 
            // Open the file and read its content
            using (var fileStream = File.OpenRead(filePath))
            {
                // Buffer to read the file
                byte[] buffer = new byte[4096];
                int sourceBytes;
 
                do
                {
                    // Copy the buffer to the zip output stream
                    sourceBytes = fileStream.Read(buffer, 0, buffer.Length);
                    zipOutputStream.Write(buffer, 0, sourceBytes);
                } while (sourceBytes > 0);
            }
        }
 
        foreach (var directoryName in Directory.GetDirectories(directoryPath))
        {
            ProcessDirectory(zipOutputStream, path, directoryName.Substring(path.Length + 1));
        }
    }
}
 
// 使用方法:
// ZipHelper.ZipDirectory("要壓縮的資料夾路徑", "輸出的壓縮檔案路徑.zip");

相關文章