前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >浅谈.Net Framework中压缩和解压

浅谈.Net Framework中压缩和解压

作者头像
小蜜蜂
发布2019-07-23 15:30:23
1.3K0
发布2019-07-23 15:30:23
举报
文章被收录于专栏:明丰随笔

1. 类层次结构

.Net Framework在下面两个类库中实现了压缩文件和解压文件的功能。

代码语言:javascript
复制
System.IO.Compression.dll
System.IO.Compression.FileStream.dll

这里列出了一系列的类支持压缩文件和提取文件等功能:

下面对这5个类的用途一一描述。

ZipFile类

一个工具类,提供创建、提取和打开zip存档的静态方法。

代码语言:javascript
复制
//根据目录创建zip存档
public static void CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName)
//根据zip存档,解压到指定文件夹
public static void ExtractToDirectory(string sourceArchiveFileName, string destinationDirectoryName)
//根据zip存档的路径,开打zip存档,并返回ZipArchive对象
public static ZipArchive Open(string archiveFileName, ZipArchiveMode mode)
public enum ZipArchiveMode
{
  Read,
  Create,
  Update
}

ZipArchive类

表示压缩文件的压缩包,采用zip存档格式。

属性:

代码语言:javascript
复制
//zip存档中所有文件信息
public ReadOnlyCollection<ZipArchiveEntry> Entries
//zip存档的打开方式
public ZipArchiveMode Mode

构造方法:

代码语言:javascript
复制
public ZipArchive(Stream stream)
public ZipArchive(Stream stream, ZipArchiveMode mode)

实例方法:

代码语言:javascript
复制
//在zip存档中新建一个文件
public ZipArchiveEntry CreateEntry(string entryName)
//在zip存档中获取一个文件
public ZipArchiveEntry GetEntry(string entryName)
//关闭zip存档对象
public void Dispose()

ZipArchiveEntry类

表示zip存档中的压缩文件。

属性:

代码语言:javascript
复制
//它属于的zip存档对象
public ZipArchive Archive
//文件数据流的长度
public long Length
//文件数据流压缩之后的长度
public long CompressedLength
//文件名称
public string Name
//文件相对于zip存档的路径
public string FullName
//文件最后的写入时间
public DateTimeOffset LastWriteTime

实例方法:

代码语言:javascript
复制
//从zip存档中删除当前的压缩文件
public void Delete()
//打开当前的压缩文件,返回流
public Stream Open()

GZipStream类

提供用于压缩和解压缩流的方法和属性。

构造方法:

代码语言:javascript
复制
public GZipStream(Stream stream, CompressionMode mode)
public enum CompressionMode
{
  Decompress,
  Compress
}

属性:

代码语言:javascript
复制
public Stream BaseStream
public override bool CanRead
public override bool CanSeek
public override bool CanWrite

实例方法:

代码语言:javascript
复制
//从缓冲区同步到设备
public override void Flush()
//读取基础流数据,然后解压,最后保存到array数组
public override int Read(byte[] array, int offset, int count)
//将字节从指定的字节数组取出,然后进行压缩,最后写入基础流。
public override void Write(byte[] array, int offset, int count)

DeflateStream类

提供使用deflate算法压缩和解压缩流的方法和属性。

构造方法:

代码语言:javascript
复制
public DeflateStream(Stream stream, CompressionMode mode)

属性:

代码语言:javascript
复制
public Stream BaseStream
public override bool CanRead
public override bool CanSeek
public override bool CanWrite

实例方法:

代码语言:javascript
复制
public override void Flush()
public override int Read(byte[] array, int offset, int count)
public override void Write(byte[] array, int offset, int count)

2. ZipFile类

ZipFile类是一个工具类,它有许多静态方法,可以帮助打开zip文件、提取数据、将目录压缩成zip文件、将zip文件提取到文件夹等等。

下面使用ZipFile类的方法将文件夹压缩到zip文件中,然后将该zip文件解压缩到其他文件夹。

代码如下:

代码语言:javascript
复制
string inputDir = @"C:\test\inputdir";
string zipPath = @"C:\test\data.zip";
string extractPath = @"C:\test\outputdir";
//将目录压缩成zip文件
ZipFile.CreateFromDirectory(inputDir, zipPath);
//将zip文件提取到文件夹
ZipFile.ExtractToDirectory(zipPath, extractPath);

运行结果:

打开data.zip如下:

3. ZipArchive类

ZipArchive对象表示以zip文件格式打包的压缩文件。可以通过ZipFile类的OpenRead方法返回ZipArchive对象。通过ZipArchive对象可以读取压缩在zip存档中的文件。

下面的示例,列出了zip存档中包含的文件。

代码语言:javascript
复制
string zipPath = "c:/test/data.zip";
using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
  // Fetch the list of ZipArchiveEntry(s).
  foreach (ZipArchiveEntry entry in archive.Entries)
  {
    Console.WriteLine("Entry:");
    //文件名
    Console.WriteLine("  Name = " + entry.Name);
    //存档中的相对路径和文件名
    Console.WriteLine("  FullName = " + entry.FullName);
  }
}

运行的结果:

提取zip存档中的文件到指定路径:

代码语言:javascript
复制
string zipPath = "c:/test/data.zip";
// Output Directory to unzip.
string extractPath = "c:/test/extract";
// if it doesn't exist, create
if (!Directory.Exists(extractPath))
{
  Directory.CreateDirectory(extractPath);
}

using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
  foreach (ZipArchiveEntry entry in archive.Entries)
  {
    Console.WriteLine("Found: " + entry.FullName);
    // Find entries ends with .docx
    if (entry.FullName.EndsWith(".docx", StringComparison.OrdinalIgnoreCase))
    {
      // ie: document/Dotnet.docx
      Console.WriteLine(" - Extract entry: " + entry.FullName);
      // C:/test/extract/documents/Dotnet.docx  ...
      string entryOuputPath = Path.Combine(extractPath, entry.FullName);
      Console.WriteLine(" - Entry Ouput Path: " + entryOuputPath);
      FileInfo fileInfo = new FileInfo(entryOuputPath);
      // Make sure the directory containing this file exists.
      // ie: C:/test/extract/documents
      fileInfo.Directory.Create();
      // Overwrite old file if it already exists.
      entry.ExtractToFile(entryOuputPath, true);
    }
  }
}

运行的结果:

还可以将文件放入可用的zip存档中。

代码语言:javascript
复制
string zipPath = "C:/test/data.zip";
// Open stream to read zip file.
using (FileStream zipStream = new FileStream(zipPath, FileMode.Open))
{
  // Create ZipArchive object.
  using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Update))
  {
    // Add entry to ZipArchive.
    ZipArchiveEntry readmeEntry = archive.CreateEntry("note/Note.txt");
    // Create stream to write content to entry.
    using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
    {
      writer.WriteLine("## Note.txt");
      writer.WriteLine("========================");
    }
  }
}

运行的结果:

回顾本文:

FCL中5个类类层次结构

这5个类的用途和成员信息

将目录压缩成zip文件

将zip文件提取到文件夹

通过ZipArchive对象读取压缩在zip存档中的文件

提取zip存档中的文件

在现有zip存档中添加新文件

-纸上得来终觉浅,绝知此事要躬行-

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-07-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 明丰随笔 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
文件存储
文件存储(Cloud File Storage,CFS)为您提供安全可靠、可扩展的共享文件存储服务。文件存储可与腾讯云服务器、容器服务、批量计算等服务搭配使用,为多个计算节点提供容量和性能可弹性扩展的高性能共享存储。腾讯云文件存储的管理界面简单、易使用,可实现对现有应用的无缝集成;按实际用量付费,为您节约成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档