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 @   qingjiawen  阅读(114)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2023-05-28 Visual Studio 扩展
点击右上角即可分享
微信分享提示