ZipArchive 的使用

时间:2022-07-17 20:28:20

新建一个项目,首先添加 System.IO.Compression.FileSystem 引用。

解压文件

using System.IO.Compression;
namespace cl
{
static void Main()
{
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
}

压缩单个文件

using System;
using System.IO.Compression; namespace cl
{
sealed class ZipCreater
{
static void Main()
{
using (var zip = ZipFile.Open("ZipCreater.zip", ZipArchiveMode.Create))
{
zip.CreateEntryFromFile(@"C:\work\ZipCreater.cs", "ZipCreater.cs");
zip.CreateEntryFromFile("ZipCreater.exe", "ZipCreater.exe");
}
}
}
}

压缩文件夹

using System;
using System.IO.Compression; namespace cl
{
sealed class Zip
{
static void Main(string[] args)
{
if (args.Length != )
{
Console.WriteLine("Usage: Zip zip-file-name directory-name");
return;
}
try { ZipFile.CreateFromDirectory(args[], args[]); }
catch (Exception ex) { Console.Error.WriteLine(ex.Message); }
}
}
}

参考文章:

浅谈 ZipArchive 类 - 银河 - 博客园
http://www.cnblogs.com/skyivben/archive/2012/03/09/2388482.html