TypechoJoeTheme

至尊技术网

统计
登录
用户名
密码
/
注册
用户名
邮箱

在.NET中利用原生方法实现文件压缩与解压的完整指南

2025-06-13
/
0 评论
/
4 阅读
/
正在检测是否收录...
06/13

1. 引入必要的命名空间

在开始之前,确保你的项目中已经引用了System.IO.CompressionSystem.IO.Compression.FileSystem这两个命名空间。

csharp using System; using System.IO; using System.IO.Compression;

2. 文件压缩

2.1 创建压缩文件的方法

要创建一个压缩文件,你可以使用ZipFile类的CreateFromDirectory方法,该方法可以将一个目录及其子目录中的所有文件压缩到一个ZIP文件中。

csharp public void CompressDirectoryToZip(string sourceDirectoryPath, string zipFilePath) { // 创建ZIP文件路径 string zipFileName = Path.GetFileName(zipFilePath); // 设置压缩级别,例如9表示最高压缩率但最慢速度 int compressionLevel = 9; using (ZipArchive archive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create)) { ZipFileInfo zipFileInfo = new ZipFileInfo(zipFileName); // 设置文件名和压缩级别等信息 archive.CreateEntryFromFile(sourceDirectoryPath, zipFileInfo); // 创建条目并从目录中添加文件到ZIP中 } }

2.2 示例:压缩单个文件到ZIP中

如果你需要只压缩单个文件,可以使用ZipFile.CreateEntryFromFile方法:
csharp public void CompressSingleFileToZip(string sourceFilePath, string zipFilePath, string entryName) { using (ZipArchive archive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create)) { ZipEntry zipEntry = archive.CreateEntry(entryName); // 创建条目并设置名称,默认为源文件名称或指定名称 using (Stream entryStream = zipEntry.Open()) // 打开条目流以写入数据到ZIP文件中 { // 可以写入到该流的数据即被压缩到ZIP文件中 using (FileStream sourceStream = File.OpenRead(sourceFilePath)) // 打开要压缩的文件流 // 将源文件流的数据复制到ZIP条目流中 sourceStream.CopyTo(entryStream); sourceStream.Close(); // 关闭源文件流和条目流 } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }}

压缩性能优化跨平台.NET解压内存流ZipArchiveModeSystem.IO.Compression
朗读
赞(0)
版权属于:

至尊技术网

本文链接:

https://www.zzwws.cn/archives/29598/(转载时请注明本文出处及文章链接)

评论 (0)