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

c#使用SevenZipSharp实现压缩文件和目录

封装了一个类,方便使用SevenZipSharp,支持加入进度显示事件。

双重加密压缩工具范例:

using SevenZip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ProcessItems
{class SevenZipSharpUser{// 假设这是某个类中的一个事件定义public  event EventHandler<ProgressEventArgs> ProgressUpdated = null;public  static bool SetSetLibraryPath(){//设置库路径string currentDirectory = AppDomain.CurrentDomain.BaseDirectory;string dllPath = GetAppropriate7zDllPath(currentDirectory);if (!File.Exists(dllPath)){return false;}SevenZipSharpUser.SetSetLibraryPath(dllPath);return true;}public static void SetSetLibraryPath(string s7zDllPath){SevenZipBase.SetLibraryPath(s7zDllPath);}public bool CompressItem(string inputItem, string outputFile, string password = null){string directory = Path.GetDirectoryName(outputFile);if (!Directory.Exists(directory)){Directory.CreateDirectory(directory);}if (Directory.Exists(inputItem)){return CompressDir(inputItem, outputFile, password);}else if (File.Exists(inputItem)){return CompressFile(inputItem, outputFile, password);}return false;}public bool DoubleCompressItem(string inputItem, string outputFile, string password1 = null, string password2 = null){string directory = Path.GetDirectoryName(outputFile);string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(outputFile);string sFirstDstPath = Path.Combine(directory, $"{fileNameWithoutExtension}{".7zx"}");CompressItem(inputItem, sFirstDstPath, password1);CompressItem(sFirstDstPath, outputFile, password2);File.Delete(sFirstDstPath);return false;}public bool ExtractItem(string inputItem, string outputDir, string password = null){// 确保输出目录存在string directory = Path.GetDirectoryName(outputDir);if (!Directory.Exists(directory)){Directory.CreateDirectory(directory);}// 检查输入文件是否存在if (!File.Exists(inputItem)){Console.WriteLine($"输入文件不存在: {inputItem}");return false;}try{// 使用 SevenZipExtractor 打开 .7z 文件if (string.IsNullOrEmpty(password)){using (var extractor = new SevenZipExtractor(inputItem)){// 提取所有文件到输出目录extractor.ExtractArchive(outputDir);}}else{using (var extractor = new SevenZipExtractor(inputItem, password)){// 提取所有文件到输出目录extractor.ExtractArchive(outputDir);}}// 解压成功return true;}catch (Exception ex){// 处理异常,例如密码错误或文件损坏Console.WriteLine($"解压文件时发生错误: {ex.Message}");return false;}}public string GetUniqueFilePath(string filePath){string directory = Path.GetDirectoryName(filePath);string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);string extension = Path.GetExtension(filePath);int counter = 1;string newFilePath = filePath;while (File.Exists(newFilePath)){newFilePath = Path.Combine(directory, $"{fileNameWithoutExtension}{counter}{extension}");counter++;}return newFilePath;}public bool CompressFile(string inputFile, string outputFile, string password = null){try{// 检查输入文件是否存在if (!File.Exists(inputFile)){throw new FileNotFoundException("输入文件不存在。", inputFile);}// 创建 SevenZipCompressor 实例var compressor = new SevenZipCompressor();// 设置压缩级别和档案格式compressor.CompressionLevel = CompressionLevel.Normal;compressor.ArchiveFormat = OutArchiveFormat.SevenZip;// 订阅进度更新事件if (ProgressUpdated != null){compressor.Compressing += ProgressUpdated;}// 压缩文件compressor.CompressFilesEncrypted(outputFile, password, inputFile);if (ProgressUpdated != null){compressor.Compressing -= ProgressUpdated;}// 压缩成功后返回 truereturn true;}catch (Exception ex){// 在发生异常时记录日志、抛出异常或返回 false// 这里简单地返回 false,但你可以根据需要更改此行为Console.WriteLine($"压缩文件时发生错误: {ex.Message}");return false;}finally{}}public bool CompressDir(string stInputDir, string stOutputFile, string stPwd){try{// 检查输入文件是否存在if (!Directory.Exists(stInputDir)){throw new FileNotFoundException("输入目录不存在。", stInputDir);}// 创建 SevenZipCompressor 实例var compressor = new SevenZipCompressor();// 设置压缩级别和档案格式compressor.CompressionLevel = CompressionLevel.Normal;compressor.ArchiveFormat = OutArchiveFormat.SevenZip;// 订阅进度更新事件if (ProgressUpdated != null){compressor.Compressing += ProgressUpdated;}// 压缩文件compressor.CompressDirectory(stInputDir, stOutputFile, stPwd);if (ProgressUpdated != null){compressor.Compressing -= ProgressUpdated;}// 压缩成功后返回 truereturn true;}catch (Exception ex){// 在发生异常时记录日志、抛出异常或返回 false// 这里简单地返回 false,但你可以根据需要更改此行为Console.WriteLine($"压缩文件时发生错误: {ex.Message}");return false;}finally{}}private static string GetAppropriate7zDllPath(string basePath){string dllName = "7z.dll";string dllPath = Path.Combine(basePath, dllName);// Check if the system is 64-bit or 32-bitif (Environment.Is64BitOperatingSystem){// If the system is 64-bit, check for a specific 64-bit version of the DLLstring dll64Path = Path.Combine(basePath, "7z.dll"); // Example name for 64-bit versionif (File.Exists(dll64Path)){return dll64Path;}// If the specific 64-bit version is not found, fall back to the generic name}else{// If the system is 32-bit, check for a specific 32-bit version of the DLLstring dll32Path = Path.Combine(basePath, "7-zip32.dll"); // Example name for 32-bit versionif (File.Exists(dll32Path)){return dll32Path;}// If the specific 32-bit version is not found, fall back to the generic name}// If neither specific version is found, return the generic DLL name (which might be a universal version or an error)return dllPath;}}
}

使用方法:

            //设置库if (!SevenZipSharpUser.SetSetLibraryPath()){MessageBox.Show("7z.dll库引用失败!", "错误!", MessageBoxButtons.OK, MessageBoxIcon.Error);}//这里是处理任务逻辑开始========start===========if (itemInfo.bDoubleCompress){szu.DoubleCompressItem(itemInfo.sItemPath, itemInfo.sDstPath, itemInfo.sPassword1, itemInfo.sPassword2);}else{szu.CompressItem(itemInfo.sItemPath, itemInfo.sDstPath, itemInfo.sPassword1);}//这里是处理任务逻辑结束========end=============

相关文章:

c#使用SevenZipSharp实现压缩文件和目录

封装了一个类&#xff0c;方便使用SevenZipSharp&#xff0c;支持加入进度显示事件。 双重加密压缩工具范例&#xff1a; using SevenZip; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.…...

【从0带做】基于Springboot3+Vue3的高校食堂点餐系统

大家好&#xff0c;我是武哥&#xff0c;最近给大家手撸了一个基于SpringBoot3Vue3的高校食堂点餐系统&#xff0c;可用于毕业设计、课程设计、练手学习&#xff0c;系统全部原创&#xff0c;如有遇到网上抄袭站长的&#xff0c;欢迎联系博主~ 详细介绍 https://www.javaxm.c…...

2025年01月09日Github流行趋势

1. 项目名称&#xff1a;khoj 项目地址url&#xff1a;https://github.com/khoj-ai/khoj项目语言&#xff1a;Python历史star数&#xff1a;22750今日star数&#xff1a;1272项目维护者&#xff1a;debanjum, sabaimran, MythicalCow, aam-at, eltociear项目简介&#xff1a;你…...

PostgreSQL学习笔记(二):PostgreSQL基本操作

PostgreSQL 是一个功能强大的开源关系型数据库管理系统 (RDBMS)&#xff0c;支持标准的 SQL 语法&#xff0c;并扩展了许多功能强大的操作语法. 数据类型 数值类型 数据类型描述存储大小示例值SMALLINT小范围整数&#xff0c;范围&#xff1a;-32,768 到 32,7672 字节-123INTE…...

关于内网外网,ABC类地址,子网掩码划分

本文的三个关键字是&#xff1a;内网外网&#xff0c;ABC类地址&#xff0c;子网掩码划分。围绕以下问题展开&#xff1a; 如何从ip区分外网、内网&#xff1f;win和linux系统中&#xff0c;如何查询自己的内网ip和外网ip。开发视角看内外网更多是处于安全考虑&#xff0c;接口…...

nginx 配置 本地启动

1.nginx下载地址&#xff1a;nginx: download nginx详解&#xff1a;Nginx配置终极版指南&#xff08;全网最详细&#xff09;_nginx_脚本之家 2.vue 项目打包生成dist文件里面的文件复制到下载好的nginx的html目录下 3.配置nginx配置文件 打包生成的dist前端包都是属于生产环…...

UE5 打包要点

------------------------- 1、需要环境 win sdk &#xff0c;大约3G VS&#xff0c;大约10G 不安装就无法打包&#xff0c;就是这么简单。 ----------------------- 2、打包设置 编译类型&#xff0c;开发、调试、发行 项目设置-地图和模式&#xff0c;默认地图 项目…...

OneFlow的简单介绍

OneFlow 是北京一流科技有限公司旗下的采用全新架构设计的开源工业级通用深度学习框架。以下是关于 OneFlow 的详细介绍&#xff1a; 本篇文章的目录 特点 功能 应用场景 发展历程 特点 简洁易用的接口&#xff1a;为深度学习相关的算法工程师提供一套简洁易用的用户接口…...

聊一聊 C#异步 任务延续的三种底层玩法

一&#xff1a;背景 1. 讲故事 最近聊了不少和异步相关的话题&#xff0c;有点疲倦了&#xff0c;今天再写最后一篇作为近期这类话题的一个封笔吧&#xff0c;下篇继续写我熟悉的 生产故障 系列&#xff0c;突然亲切感油然而生&#xff0c;哈哈&#xff0c;免费给别人看程序故…...

(k8s)Flannel Error问题解决!

1.问题描述 书接上回&#xff0c;我们在解决kubectl不断重启的时候引入了Flannel 网络插件&#xff0c;但是一上来就报错&#xff0c; 2.问题解决 自己的思路&#xff1a;照例开始检查 1.先检查一下目前Flannel的pod kubectl get pods --all-namespaces 2.检查 Flannel的po…...

Delaunay三角刨分算法理解及c#过程实现

Delaunay三角刨分算法理解及c#过程实现 0 引言1 关于三角剖分2 Delaunay三角剖分算法实现及对比3 结语0 引言 💻💻AI一下💻💻 三角剖分是什么? 三角剖分是一种将平面或曲面划分成三角形集合的方法。在二维平面中,给定一个平面区域(可以是多边形等),通过连接区域…...

Backend - ADO.NET(C# 操作Oracle、PostgreSQL DB)

目录 一、引入参考 1. ConfigurationManager的调用前提&#xff1a; 2. NpgsqlConnection的调用前提&#xff1a; 3. OracleConnection的调用前提&#xff1a; 二、设置数据库链接字串 1. 在App.config中设定链接数据库详情 2. 获取数据库链接字串 三、调用 1.调用Oracle数据库…...

Idea-离线安装SonarLint插件地址

地址&#xff1a; SonarQube for IDE - IntelliJ IDEs Plugin | Marketplace 选择Install Plugin from Disk..&#xff0c;选中下载好的插件&#xff0c;然后重启idea...

Leetcode Hot100 第三题 234. 回文链表

用快慢指针找到链表中间节点反转后面一段链表遍历每个节点做判断为什么是while pre: 不能写while head呢 ? 答&#xff1a;因为slow节点在反转后&#xff0c;他的前序节点除了反转之后的节点&#xff0c;之前正序的节点仍然存在的&#xff0c;即slow.pre 的next依旧是slow, 我…...

Python教程丨Python环境搭建 (含IDE安装)——保姆级教程!

工欲善其事&#xff0c;必先利其器。 学习Python的第一步不要再加收藏夹了&#xff01;提高执行力&#xff0c;先给自己装好Python。 1. Python 下载 1.1. 下载安装包 既然要下载Python&#xff0c;我们直接进入python官网下载即可 Python 官网&#xff1a;Welcome to Pyt…...

SpringBoot项目实战(39)--Beetl网页HTML文件中静态图片及CSS、JS文件的引用和展示

使用Beetl开发网页时&#xff0c;在网页中使用的CSS、JS、图片等静态资源需要进行适当的配置才可以展示。大致的过程如下&#xff1a; &#xff08;1&#xff09;首先Spring Security框架需要允许js、css、图片资源免授权访问。 &#xff08;2&#xff09;网站开发时&#xff0…...

ARIMA模型 (AutoRegressive Integrated Moving Average) 算法详解与PyTorch实现

ARIMA模型 (AutoRegressive Integrated Moving Average) 算法详解与PyTorch实现 目录 ARIMA模型 (AutoRegressive Integrated Moving Average) 算法详解与PyTorch实现1. ARIMA模型概述1.1 时间序列预测1.2 ARIMA的优势2. ARIMA的核心技术2.1 自回归 (AR)2.2 差分 (I)2.3 移动平…...

【Uniapp-Vue3】swiper滑块视图容器的用法

我们使用swiper标签就可以实现轮播图的效果。 一、swiper组件的结构 整体的轮播图使用swiper标签&#xff0c;轮播的每一页使用swiper-item标签。 <template><swiper class"swiper"><swiper-item><view class"swiper-item">111…...

allure报告修改默认语言为中文

1、项目根目录创建.py文件&#xff0c;把代码复制进去 import os from pathlib import Pathdef create_settings_js_file(directory"../pytest_mytt/reports/allures/", filenamesettings.js):# 创建或确认目录存在Path(directory).mkdir(parentsTrue, exist_okTrue…...

国产3D CAD将逐步取代国外软件

在工业软件的关键领域&#xff0c;计算机辅助设计&#xff08;CAD&#xff09;软件对于制造业的重要性不言而喻。近年来&#xff0c;国产 CAD 的发展态势迅猛&#xff0c;展现出巨大的潜力与机遇&#xff0c;正逐步改变着 CAD 市场长期由国外软件主导的格局。 国产CAD发展现状 …...

未来机器人的大脑:如何用神经网络模拟器实现更智能的决策?

编辑&#xff1a;陈萍萍的公主一点人工一点智能 未来机器人的大脑&#xff1a;如何用神经网络模拟器实现更智能的决策&#xff1f;RWM通过双自回归机制有效解决了复合误差、部分可观测性和随机动力学等关键挑战&#xff0c;在不依赖领域特定归纳偏见的条件下实现了卓越的预测准…...

OpenLayers 可视化之热力图

注&#xff1a;当前使用的是 ol 5.3.0 版本&#xff0c;天地图使用的key请到天地图官网申请&#xff0c;并替换为自己的key 热力图&#xff08;Heatmap&#xff09;又叫热点图&#xff0c;是一种通过特殊高亮显示事物密度分布、变化趋势的数据可视化技术。采用颜色的深浅来显示…...

Debian系统简介

目录 Debian系统介绍 Debian版本介绍 Debian软件源介绍 软件包管理工具dpkg dpkg核心指令详解 安装软件包 卸载软件包 查询软件包状态 验证软件包完整性 手动处理依赖关系 dpkg vs apt Debian系统介绍 Debian 和 Ubuntu 都是基于 Debian内核 的 Linux 发行版&#xff…...

如何在看板中体现优先级变化

在看板中有效体现优先级变化的关键措施包括&#xff1a;采用颜色或标签标识优先级、设置任务排序规则、使用独立的优先级列或泳道、结合自动化规则同步优先级变化、建立定期的优先级审查流程。其中&#xff0c;设置任务排序规则尤其重要&#xff0c;因为它让看板视觉上直观地体…...

从零开始打造 OpenSTLinux 6.6 Yocto 系统(基于STM32CubeMX)(九)

设备树移植 和uboot设备树修改的内容同步到kernel将设备树stm32mp157d-stm32mp157daa1-mx.dts复制到内核源码目录下 源码修改及编译 修改arch/arm/boot/dts/st/Makefile&#xff0c;新增设备树编译 stm32mp157f-ev1-m4-examples.dtb \stm32mp157d-stm32mp157daa1-mx.dtb修改…...

今日科技热点速览

&#x1f525; 今日科技热点速览 &#x1f3ae; 任天堂Switch 2 正式发售 任天堂新一代游戏主机 Switch 2 今日正式上线发售&#xff0c;主打更强图形性能与沉浸式体验&#xff0c;支持多模态交互&#xff0c;受到全球玩家热捧 。 &#x1f916; 人工智能持续突破 DeepSeek-R1&…...

智能仓储的未来:自动化、AI与数据分析如何重塑物流中心

当仓库学会“思考”&#xff0c;物流的终极形态正在诞生 想象这样的场景&#xff1a; 凌晨3点&#xff0c;某物流中心灯火通明却空无一人。AGV机器人集群根据实时订单动态规划路径&#xff1b;AI视觉系统在0.1秒内扫描包裹信息&#xff1b;数字孪生平台正模拟次日峰值流量压力…...

代码随想录刷题day30

1、零钱兑换II 给你一个整数数组 coins 表示不同面额的硬币&#xff0c;另给一个整数 amount 表示总金额。 请你计算并返回可以凑成总金额的硬币组合数。如果任何硬币组合都无法凑出总金额&#xff0c;返回 0 。 假设每一种面额的硬币有无限个。 题目数据保证结果符合 32 位带…...

PostgreSQL——环境搭建

一、Linux # 安装 PostgreSQL 15 仓库 sudo dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-$(rpm -E %{rhel})-x86_64/pgdg-redhat-repo-latest.noarch.rpm# 安装之前先确认是否已经存在PostgreSQL rpm -qa | grep postgres# 如果存在&#xff0…...

为什么要创建 Vue 实例

核心原因:Vue 需要一个「控制中心」来驱动整个应用 你可以把 Vue 实例想象成你应用的**「大脑」或「引擎」。它负责协调模板、数据、逻辑和行为,将它们变成一个活的、可交互的应用**。没有这个实例,你的代码只是一堆静态的 HTML、JavaScript 变量和函数,无法「活」起来。 …...