深度优先

这个家伙好懒,除了文章什么都没留下

0%

【CSharp】ZIP压缩流

转自:https://www.cnblogs.com/slyfox/p/11231375.html

参考资料

Overview

ZIP流是在NetFramework4.5 引入的目的是为了能够更好的操作ZIP文件,进行压缩解压等操作。与ZIP流相关的几个类是:

  1. ZipArchive 代表一个ZIP的压缩包文件
  2. ZipArchiveEntry 代表ZIP压缩包中的一个文件
  3. ZipFile 提供了一系列的静态方法来帮助用户更方便地操作ZIP文件,类似于File类的作用。

PS: 在使用之前请先添加程序集引用System.IO.CompressionSystem.IO.Compression.FileStream

ZipArchive常见操作

创建一个ZIP文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using (FileStream fs = new FileStream("myZip.zip", FileMode.Create))
{
//打开压缩包
using (ZipArchive zipArchive = new ZipArchive(fs, ZipArchiveMode.Create))
{
//创建一个条目
ZipArchiveEntry entry = zipArchive.CreateEntry("HelloWorld.txt");
//在条目中写入内容
using (StreamWriter writer = new StreamWriter(entry.Open(), Encoding.Default))
{
writer.Write("I am 鲁迅认识的那只猹! Hello World");
}
}
}

向现有的ZIP压缩包中添加文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using (FileStream fs = new FileStream("myZip.zip", FileMode.Open))
{
//打开压缩包,Mode 为Update模式
using (ZipArchive zipArchive = new ZipArchive(fs, ZipArchiveMode.Update))
{
//创建一个条目
ZipArchiveEntry entry = zipArchive.CreateEntry("AppendFile.txt");
//在条目中写入内容
using (StreamWriter writer = new StreamWriter(entry.Open(), Encoding.Default))
{
writer.Write("这是追加的内容!");
}
}
}

解压ZIP压缩包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using (FileStream fs = new FileStream("myZip.zip", FileMode.Open))
{
//打开压缩包,Mode 为Update模式
using (ZipArchive zipArchive = new ZipArchive(fs, ZipArchiveMode.Update))
{
//创建一个用来存放解压后的文件的目录
Directory.CreateDirectory("myZip");
//将所有的条目解压出来
foreach (var item in zipArchive.Entries)
{
//解压文件
item.ExtractToFile(@"myZip\" + item.Name);
}
}
}

ZipFile

方法 解释
FileZip.CreateFromDirectory 从一个目录创建ZIP压缩文件
FileZip.ExtractToDirectory 将ZIP压缩文件解压到目录中
FileZip.Open 打开一个ZIP压缩文件
FileZip.OpenRead 打开一个读取模式的ZIP压缩文件

ZipFileExtensions

ZipFileExtensions 为ZipArchive 和 ZipArchiveEntry 提供了一些更简便的方法,具体可以查看官方文档

Demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
WebClient webClient = new WebClient();

var list = new List<string>()
{
"https://img.bfsdfs.com/UploadFiles/Images/2021/202106/7d18bd27-d1ba-44e6-9f1c-cc30e9d0b8fb.jpg",
"https://img.bfsdfs.com/UploadFiles/Images/2021/202106/a79c754e-2b80-4db2-9154-5d3894ac6d90.jpg",
"https://open.weixin.qq.com/zh_CN/htmledition/res/assets/manage/Website_Information_Form.doc",
};

using (MemoryStream ms = new MemoryStream())
{
using (ZipArchive archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
{
foreach (var url in list)
{
var fileName = url.Substring(url.LastIndexOf("/") + 1);
ZipArchiveEntry readmeEntry = archive.CreateEntry(fileName);

using (Stream stream = readmeEntry.Open())
{
var bytes = webClient.DownloadData(url);
stream.Write(bytes, 0, bytes.Length);
}
}
}

using (FileStream fs = new FileStream("result.zip", FileMode.OpenOrCreate))
{
BinaryWriter w = new BinaryWriter(fs);
w.Write(ms.ToArray());
}
}