C#对.zip 存档读取和写入
Framework4.5支持
引用: System.IO.Compression.dll
,System.IO.Compression.FileSystem.dll
提取压缩文件
ZipFile.ExtractToDirectory(@"P:\files.zip", @"P:\files");
提取单个文件
using (ZipArchive zipArchive =
ZipFile.Open(@"P:\files.zip", ZipArchiveMode.Read))
{
foreach (ZipArchiveEntry entry in zipArchive.Entries)
{
if (entry.Name == "file.txt")
{
using (Stream stream = entry.Open())
{
ProcessFile(stream);
}
}
}
}
创建 .zip 存档
ZipFile.CreateFromDirectory(@"P:\files", @"P:\files.zip");
其他操作,创建压缩包内的目录
IEnumerable<string> files =
Directory.EnumerateFiles(@"P:\files", "*.cs");
using (ZipArchive zipArchive =
ZipFile.Open(@"P:\files.zip", ZipArchiveMode.Create))
{
foreach (string file in files)
{
var entryName = Path.Combine("SourceCode", Path.GetFileName(file));
zipArchive.CreateEntryFromFile(file, entryName);
}
}
https://msdn.microsoft.com/zh-cn/library/system.io.compression.zipfile(v=vs.110).aspx
https://msdn.microsoft.com/zh-cn/library/system.io.compression.ziparchive(v=vs.110).aspx
源文: https://msdn.microsoft.com/zh-cn/magazine/jj133817.aspx