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

2024-03-14 06:12

本文主要是介绍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

这篇关于C#使用SharpZipLib对文件进行压缩和解压的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/807459

相关文章

Java图片压缩三种高效压缩方案详细解析

《Java图片压缩三种高效压缩方案详细解析》图片压缩通常涉及减少图片的尺寸缩放、调整图片的质量(针对JPEG、PNG等)、使用特定的算法来减少图片的数据量等,:本文主要介绍Java图片压缩三种高效... 目录一、基于OpenCV的智能尺寸压缩技术亮点:适用场景:二、JPEG质量参数压缩关键技术:压缩效果对比

使用Python实现一键隐藏屏幕并锁定输入

《使用Python实现一键隐藏屏幕并锁定输入》本文主要介绍了使用Python编写一个一键隐藏屏幕并锁定输入的黑科技程序,能够在指定热键触发后立即遮挡屏幕,并禁止一切键盘鼠标输入,这样就再也不用担心自己... 目录1. 概述2. 功能亮点3.代码实现4.使用方法5. 展示效果6. 代码优化与拓展7. 总结1.

使用Python开发一个简单的本地图片服务器

《使用Python开发一个简单的本地图片服务器》本文介绍了如何结合wxPython构建的图形用户界面GUI和Python内建的Web服务器功能,在本地网络中搭建一个私人的,即开即用的网页相册,文中的示... 目录项目目标核心技术栈代码深度解析完整代码工作流程主要功能与优势潜在改进与思考运行结果总结你是否曾经

Linux中的计划任务(crontab)使用方式

《Linux中的计划任务(crontab)使用方式》:本文主要介绍Linux中的计划任务(crontab)使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、前言1、linux的起源与发展2、什么是计划任务(crontab)二、crontab基础1、cro

kotlin中const 和val的区别及使用场景分析

《kotlin中const和val的区别及使用场景分析》在Kotlin中,const和val都是用来声明常量的,但它们的使用场景和功能有所不同,下面给大家介绍kotlin中const和val的区别,... 目录kotlin中const 和val的区别1. val:2. const:二 代码示例1 Java

C++变换迭代器使用方法小结

《C++变换迭代器使用方法小结》本文主要介绍了C++变换迭代器使用方法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1、源码2、代码解析代码解析:transform_iterator1. transform_iterat

C++中std::distance使用方法示例

《C++中std::distance使用方法示例》std::distance是C++标准库中的一个函数,用于计算两个迭代器之间的距离,本文主要介绍了C++中std::distance使用方法示例,具... 目录语法使用方式解释示例输出:其他说明:总结std::distance&n编程bsp;是 C++ 标准

vue使用docxtemplater导出word

《vue使用docxtemplater导出word》docxtemplater是一种邮件合并工具,以编程方式使用并处理条件、循环,并且可以扩展以插入任何内容,下面我们来看看如何使用docxtempl... 目录docxtemplatervue使用docxtemplater导出word安装常用语法 封装导出方

SpringBoot3实现Gzip压缩优化的技术指南

《SpringBoot3实现Gzip压缩优化的技术指南》随着Web应用的用户量和数据量增加,网络带宽和页面加载速度逐渐成为瓶颈,为了减少数据传输量,提高用户体验,我们可以使用Gzip压缩HTTP响应,... 目录1、简述2、配置2.1 添加依赖2.2 配置 Gzip 压缩3、服务端应用4、前端应用4.1 N

Linux换行符的使用方法详解

《Linux换行符的使用方法详解》本文介绍了Linux中常用的换行符LF及其在文件中的表示,展示了如何使用sed命令替换换行符,并列举了与换行符处理相关的Linux命令,通过代码讲解的非常详细,需要的... 目录简介检测文件中的换行符使用 cat -A 查看换行符使用 od -c 检查字符换行符格式转换将