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

C#中压缩文件夹,及其内容

压缩包格式,本文主要用于说明如何使用代码 文件或文件夹压缩为 zip压缩包及其解压操作,
下面分两个版本进行实现

1.简单版本

   bool DoCompressDirectoryInfo(string folderPath){try{var zipFilePath = $"{folderPath}.zip";var directoryInfo = new DirectoryInfo(zipFilePath);if (directoryInfo.Exists){directoryInfo.Delete();}if (directoryInfo.Parent != null){directoryInfo = directoryInfo.Parent;}System.IO.Compression.ZipFile.CreateFromDirectory(folderPath, zipFilePath, CompressionLevel.Optimal, false);return true;}catch (Exception ex){_logger.LogError(ex, $"压缩文件失败,{folderPath}!");return false;}}

2.第二种复杂版本

帮助类

class FolderCompressor
{public stati  bool DoCompressDirectoryInfo(string folderPath){try{var zipFilePath = $"{folderPath}.zip";FolderCompressor.CompressFolder(folderPath, zipFilePath);return true;}catch (Exception ex){_logger.LogError(ex, $"压缩文件失败,{folderPath}!");return false;}}public static void CompressFolder(string sourceFolderPath, string destinationZipFilePath){using FileStream zipToOpen = new FileStream(destinationZipFilePath, FileMode.Create);using ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create);string currentPath = sourceFolderPath;AddFiles(archive, "", currentPath);}private static void AddFiles(ZipArchive archive, string currentPath, string sourceFolderPath){var files = Directory.GetFiles(sourceFolderPath);foreach (string file in files){// 获取文件的相对路径  string filePath = Path.GetFullPath(file);string relativePath = filePath.Substring(sourceFolderPath.Length).TrimStart(Path.DirectorySeparatorChar);// 将文件添加到ZIP存档  var readOnlyEntry = archive.CreateEntry(Path.Combine(currentPath, relativePath));using var fileToCompress = File.OpenRead(file);using var entryStream = readOnlyEntry.Open();fileToCompress.CopyTo(entryStream);}// 递归处理子文件夹  string[] directories = Directory.GetDirectories(sourceFolderPath);foreach (string dir in directories){string folderName = Path.GetFileName(dir);AddFiles(archive, Path.Combine(currentPath, folderName), dir);}}
}

调用时候最好用 DoCompressDirectoryInfo方法

http://www.lryc.cn/news/406712.html

相关文章:

  • 机器学习 | 回归算法原理——多项式回归
  • 力扣224【基本计算器】
  • 【Linux】HTTP 协议
  • @Builder注释导致@RequestBody的前端json反序列化失败,HTTP400
  • 网络学习|如何理解服务的端口号
  • 《0基础》学习Python——第十八讲__爬虫/<1>
  • NFTScan 浏览器现已支持 .mint 域名搜索功能!
  • Git基本原理讲解、常见命令、Git版本回退、Git抛弃本地分支拉取仓库最新分支
  • 前端网页打开PC端本地的应用程序实现方案
  • 遇到not allow unquoted fieldName怎么办
  • IDEA安装并使用通义灵码
  • <数据集>AffectNet表情识别数据集<目标检测>
  • ThinkPHP对接易联云打印
  • JavaScript轮播图
  • 修复SteamUI.dll加载失败的指南,快速修复failed to load steamui.dll
  • PCL Local Surface Patches 关键点提取
  • Vue与ASP.NET Core Web Api设置localhost与本地ip地址皆可访问
  • Android 线程池的面试题 线程线程池面试题
  • Flink时间和窗口
  • LLaMA模型量化方法优化:提高性能与减小模型大小
  • 前端CSS实现卡片抽奖效果
  • Java在for循环中修改集合
  • Java小白入门到实战应用教程-运算符详解
  • secureCRT同时在所有已打开窗口执行命令、mac-os下使用的SecureCRT版本 以及 SecureCRT一段时间不操作没有响应的问题
  • 增材制造与智能制造关系
  • Google Test 学习笔记(简称GTest)
  • 不可变集合
  • 景区AR导航营销系统:技术解决方案与实施效益分析
  • MATLAB的基础知识
  • Redis-高级实战案例