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

posted @   高效养猪倌  阅读(7679)  评论(0编辑  收藏  举报
编辑推荐:
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
阅读排行:
· 本地部署 DeepSeek:小白也能轻松搞定!
· 如何给本地部署的DeepSeek投喂数据,让他更懂你
· 从 Windows Forms 到微服务的经验教训
· 李飞飞的50美金比肩DeepSeek把CEO忽悠瘸了,倒霉的却是程序员
· 超详细,DeepSeek 接入PyCharm实现AI编程!(支持本地部署DeepSeek及官方Dee
点击右上角即可分享
微信分享提示