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中的ConcurrentBitSet使用小结

《Java中的ConcurrentBitSet使用小结》本文主要介绍了Java中的ConcurrentBitSet使用小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录一、核心澄清:Java标准库无内置ConcurrentBitSet二、推荐方案:Eclipse

Go语言结构体标签(Tag)的使用小结

《Go语言结构体标签(Tag)的使用小结》结构体标签Tag是Go语言中附加在结构体字段后的元数据字符串,用于提供额外的属性信息,这些信息可以通过反射在运行时读取和解析,下面就来详细的介绍一下Tag的使... 目录什么是结构体标签?基本语法常见的标签用途1.jsON 序列化/反序列化(最常用)2.数据库操作(

Java中ScopeValue的使用小结

《Java中ScopeValue的使用小结》Java21引入的ScopedValue是一种作用域内共享不可变数据的预览API,本文就来详细介绍一下Java中ScopeValue的使用小结,感兴趣的可以... 目录一、Java ScopedValue(作用域值)详解1. 定义与背景2. 核心特性3. 使用方法

spring中Interceptor的使用小结

《spring中Interceptor的使用小结》SpringInterceptor是SpringMVC提供的一种机制,用于在请求处理的不同阶段插入自定义逻辑,通过实现HandlerIntercept... 目录一、Interceptor 的核心概念二、Interceptor 的创建与配置三、拦截器的执行顺

Python在二进制文件中进行数据搜索的实战指南

《Python在二进制文件中进行数据搜索的实战指南》在二进制文件中搜索特定数据是编程中常见的任务,尤其在日志分析、程序调试和二进制数据处理中尤为重要,下面我们就来看看如何使用Python实现这一功能吧... 目录简介1. 二进制文件搜索概述2. python二进制模式文件读取(rb)2.1 二进制模式与文本

SQL Server 中的表进行行转列场景示例

《SQLServer中的表进行行转列场景示例》本文详细介绍了SQLServer行转列(Pivot)的三种常用写法,包括固定列名、条件聚合和动态列名,文章还提供了实际示例、动态列数处理、性能优化建议... 目录一、常见场景示例二、写法 1:PIVOT(固定列名)三、写法 2:条件聚合(CASE WHEN)四、

C#中checked关键字的使用小结

《C#中checked关键字的使用小结》本文主要介绍了C#中checked关键字的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录✅ 为什么需要checked? 问题:整数溢出是“静默China编程”的(默认)checked的三种用

C#中预处理器指令的使用小结

《C#中预处理器指令的使用小结》本文主要介绍了C#中预处理器指令的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录 第 1 名:#if/#else/#elif/#endif✅用途:条件编译(绝对最常用!) 典型场景: 示例

C#实现将XML数据自动化地写入Excel文件

《C#实现将XML数据自动化地写入Excel文件》在现代企业级应用中,数据处理与报表生成是核心环节,本文将深入探讨如何利用C#和一款优秀的库,将XML数据自动化地写入Excel文件,有需要的小伙伴可以... 目录理解XML数据结构与Excel的对应关系引入高效工具:使用Spire.XLS for .NETC

C#如何在Excel文档中获取分页信息

《C#如何在Excel文档中获取分页信息》在日常工作中,我们经常需要处理大量的Excel数据,本文将深入探讨如何利用Spire.XLSfor.NET,高效准确地获取Excel文档中的分页信息,包括水平... 目录理解Excel中的分页机制借助 Spire.XLS for .NET 获取分页信息为什么选择 S