c# 将文件夹下的文件压缩7zip
时间: 2024-09-18 22:05:38 浏览: 34
在C#中,你可以利用`System.IO.Compression.ZipFile`类来创建一个ZIP压缩文件,包含特定文件夹下的所有内容。以下是一个基本示例,展示如何压缩指定文件夹:
```csharp
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
public void CompressFolderToZip(string sourceFolder, string destinationZip)
{
if (!Directory.Exists(sourceFolder))
{
throw new ArgumentException("Source folder does not exist.");
}
using (var archive = new ZipOutputStream(File.Create(destinationZip)))
{
var directoryInfo = new DirectoryInfo(sourceFolder);
foreach (FileInfo file in directoryInfo.GetFiles())
{
AddFileToZip(archive, file.FullName);
}
// 如果有子文件夹也需要压缩
foreach (DirectoryInfo subDirectory in directoryInfo.GetDirectories())
{
AddDirectoryToZip(archive, subDirectory.FullName);
}
}
}
private static void AddFileToZip(ZipOutputStream archive, string sourceFilePath)
{
ZipEntry entry = new ZipEntry(Path.GetFileName(sourceFilePath));
archive.PutNextEntry(entry);
using (FileStream sourceStream = File.OpenRead(sourceFilePath))
{
ArchiveEntry tempEntry = archive.GetNextEntry();
byte[] buffer = new byte[4096];
int len;
while ((len = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
{
archive.Write(buffer, 0, len);
}
tempEntry.IsUnicodeText = true; // 设置为UTF8文本,如果是二进制文件,可以去掉这行
tempEntry.Close();
}
archive.EntryClose();
}
private static void AddDirectoryToZip(ZipOutputStream archive, string sourceDirectoryPath)
{
ZipEntry entry = new ZipEntry(sourceDirectoryPath.Substring(sourceDirectoryPath.LastIndexOf('/') + 1) + "/");
archive.PutNextEntry(entry);
// 空目录需要特殊处理
archive.SetMethod(ZipEntry.DEFLATED);
archive.WriteByte((byte)' ');
archive.WriteByte((byte)' ');
archive.WriteByte((byte)' ');
archive.WriteByte((byte)' ');
archive.CloseEntry();
}
```
记得安装SharpZipLib库(NuGet包管理器中搜索ICSharpCode.SharpZipLib即可),然后根据实际情况修改源文件夹路径和目标压缩文件路径。
阅读全文