当前位置: 首页 > article >正文

C#使用SharpZipLib对文件进行压缩和解压

C#使用SharpZipLib对文件进行压缩和解压

使用SharpZipLib库

编写SharpZipLibHelper帮助类

using ICSharpCode.SharpZipLib.Zip;

namespace SharpZipLib_Project
{
    public class SharpZipLibHelper
    {
        /// <summary>
        /// 多个文件或文件夹压缩
        /// </summary>
        /// <param name="sourcePaths">文件或文件夹名称</param>
        /// <param name="zipFilePath">压缩文件夹名称</param>
        public static string CompressFilesAndDirectories(string[] sourcePaths, string zipFilePath)
        {
            try
            {
                using (FileStream fsOut = File.Create(zipFilePath))
                {
                    using (ZipOutputStream zipStream = new ZipOutputStream(fsOut))
                    {
                        foreach (string sourcePath in sourcePaths)
                        {
                            if (Directory.Exists(sourcePath))
                            {
                                CompressDirectoryRecursive(sourcePath, zipStream);
                            }
                            else if (File.Exists(sourcePath))
                            {
                                CompressFile(sourcePath, zipStream);
                            }
                            else
                            {
                                Console.WriteLine($"Path '{sourcePath}' does not exist.");
                            }
                        }
                    }
                }
                return "成功";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        /// <summary>
        /// 向压缩文件添加文件
        /// </summary>
        /// <param name="sourceFilePath"></param>
        /// <param name="zipStream"></param>
        /// <returns></returns>
        private static string CompressFile(string sourceFilePath, ZipOutputStream zipStream)
        {
            try
            {
                string entryName = Path.GetFileName(sourceFilePath);
                ZipEntry newEntry = new ZipEntry(entryName);
                zipStream.PutNextEntry(newEntry);

                byte[] buffer = new byte[4096];
                using (FileStream fsIn = File.OpenRead(sourceFilePath))
                {
                    int sourceBytes;
                    do
                    {
                        sourceBytes = fsIn.Read(buffer, 0, buffer.Length);
                        zipStream.Write(buffer, 0, sourceBytes);
                    } while (sourceBytes > 0);
                }
                return "成功";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        /// <summary>
        /// 向压缩文件添加文件夹
        /// </summary>
        /// <param name="rootDirectoryPath"></param>
        /// <param name="currentDirectoryPath"></param>
        /// <param name="zipStream"></param>
        /// <returns></returns>
        private static string CompressDirectoryRecursive(string sourceDirectoryPath, ZipOutputStream zipStream)
        {
            try
            {
                string[] files = Directory.GetFiles(sourceDirectoryPath, "*", SearchOption.AllDirectories);
                string rootDirectoryName = Path.GetFileName(sourceDirectoryPath);

                // 添加文件夹本身
                ZipEntry rootDirectoryEntry = new ZipEntry(rootDirectoryName + "/");
                zipStream.PutNextEntry(rootDirectoryEntry);

                // 添加文件夹内的文件和子文件夹
                foreach (string file in files)
                {
                    string relativePath = Path.GetRelativePath(sourceDirectoryPath, file);
                    ZipEntry newEntry = new ZipEntry(rootDirectoryName + "/" + relativePath);
                    zipStream.PutNextEntry(newEntry);

                    byte[] buffer = new byte[4096];
                    using (FileStream fsIn = File.OpenRead(file))
                    {
                        int sourceBytes;
                        while ((sourceBytes = fsIn.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            zipStream.Write(buffer, 0, sourceBytes);
                        }
                    }
                }
                return "成功";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        /// <summary>
        /// 解压文件
        /// </summary>
        /// <param name="zipFilePath">压缩文件地址</param>
        /// <param name="extractPath">解压文件夹</param>
        /// <returns></returns>
        public static string DecompressFile(string zipFilePath, string extractPath)
        {
            try
            {
                if (!Directory.Exists(extractPath))
                    Directory.CreateDirectory(extractPath);

                using (FileStream fsIn = new FileStream(zipFilePath, FileMode.Open, FileAccess.Read))
                {
                    using (ZipInputStream zipStream = new ZipInputStream(fsIn))
                    {
                        ZipEntry entry;
                        while ((entry = zipStream.GetNextEntry()) != null)
                        {
                            string entryFileName = Path.Combine(extractPath, entry.Name);
                            string directoryName = Path.GetDirectoryName(entryFileName);

                            if (directoryName.Length > 0 && !Directory.Exists(directoryName))
                                Directory.CreateDirectory(directoryName);

                            if (entry.IsFile)
                            {
                                using (FileStream fsOut = File.Create(entryFileName))
                                {
                                    byte[] buffer = new byte[4096];
                                    int sourceBytes;
                                    while ((sourceBytes = zipStream.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        fsOut.Write(buffer, 0, sourceBytes);
                                    }
                                }
                            }
                        }
                    }
                }
                return "成功";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}

如何使用工具类

private void button1_Click(object sender, EventArgs e)
{
    // 压缩文件
    string[] sourcePaths = { "example.txt", "Example", "example1.txt"};
    string str = SharpZipLibHelper.CompressFilesAndDirectories(sourcePaths, "example.zip");
    if (str != "成功")
    {
        MessageBox.Show($"压缩失败: {str}");
    }
    else
    {
        MessageBox.Show("压缩成功!");
    }
}

private void button2_Click(object sender, EventArgs e)
{
    // 解压缩文件
    string str = SharpZipLibHelper.DecompressFile("example.zip", "extracted_files");
    if (str != "成功")
    {
        MessageBox.Show($"解压失败: {str}");
    }
    else
    {
        MessageBox.Show("解压成功!");
    }
}

备注: 这种压缩方法无法压缩空的文件夹,因为空的文件夹里面没有文件路径,所有会自动忽略.如果需要添加空文件夹需要自己先判断目录是否为空,然后自己在压缩文件中创建就可以了

2024.3.13


http://www.kler.cn/a/271714.html

相关文章:

  • 前端axios拦截器
  • RDK X5运行DeepSeek-R1-Distill-Qwen-1.5B,体验长思维链的语言大模型!
  • 展示统计信息收集情况
  • CTFSHOW-WEB入门-命令执行29-32
  • 《多阶段渐进式图像修复》学习笔记
  • openeuler 22.03 lts sp4 使用 cri-o 和 静态 pod 的方式部署 k8s-v1.32.0 高可用集群
  • NCV8705MTADJTCG稳压器芯片中文资料规格书PDF数据手册引脚图图片价格功能
  • 鸿蒙Harmony应用开发—ArkTS声明式开发(基础手势:Search)
  • venv uvicorn python 虚拟服务器外网无法访问
  • swagger踩坑之请求类不显示具体字段
  • Redis + Caffeine = 王炸!!
  • Spring项目-前端问题:Can‘t find variable:$
  • 通用的springboot web jar包执行脚本,释放端口并执行jar包
  • PHP修改默认上传文件缓存位置
  • PC-DARTS: PARTIAL CHANNEL CONNECTIONS FOR MEMORY-EFFICIENT ARCHITECTURE SEARCH
  • HamonyOS进度条通知
  • 请解释Redis是什么?它有哪些主要应用场景?Redis支持哪些数据类型?并描述每种数据类型的特性和使用场景。
  • 1.实用Qt:解决绘制圆角边框时,圆角锯齿问题
  • 鸿蒙Harmony应用开发—ArkTS声明式开发(容器组件:GridItem)
  • SQL注入无回显,利用DNSlog构造方式
  • 力扣-3. 无重复字符的最长子串
  • Vue+SpringBoot打造康复中心管理系统
  • Pandas中高效选择和替换操作总结
  • Kubernetes operator系列:webhook 知识学习
  • PHP8编译安装
  • RequestResponse案例