CSharp创建Zip文件并添加文件流进入,请给出代码示例
时间: 2023-05-23 13:07:33 浏览: 47
下面是使用C#创建Zip文件并添加文件流的示例代码:
```csharp
using System.IO;
using System.IO.Compression;
string zipPath = @"C:\example.zip";
string filePath = @"C:\example.txt";
using (ZipArchive archive = ZipFile.Open(zipPath, ZipArchiveMode.Create))
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
ZipArchiveEntry entry = archive.CreateEntry(Path.GetFileName(filePath));
using (Stream entryStream = entry.Open())
{
fileStream.CopyTo(entryStream);
}
}
}
```
这段代码做了以下几件事:
1. 定义了zip文件路径和要添加的文件路径。
2. 创建了一个 ZipArchive 对象并指定使用 ZipArchiveMode.Create 模式打开 zip 文件以进行写入。
3. 打开要添加的文件并将其添加为 ZipArchiveEntry 对象。
4. 将文件流复制到 ZipArchiveEntry 的流中。
5. 关闭所有打开的流。
请注意这个示例代码只添加了一个文件,您可以使用类似的方式添加多个文件。