悠悠楠杉
在.NET中利用原生方法实现文件压缩与解压的完整指南
1. 引入必要的命名空间
在开始之前,确保你的项目中已经引用了System.IO.Compression
和System.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(); // 关闭源文件流和条目流 } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }} }}