c# 文件压缩DotNetZip和SharpZipLib

 

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");

 

posted @ 2024-05-28 11:43  qingjiawen  阅读(15)  评论(0编辑  收藏  举报