如何从C#内存中的文件创建ZipArchive?

是否有可能从内存中的文件(而不是实际上在磁盘上)创建ZipArchive。

以下是用例:IEnumerable变量中接收多个文件。 我想使用ZipArchive将所有这些文件压缩在一起。 问题是ZipArchive只允许CreateEntryFromFile ,它需要一个文件路径,因为我只有内存中的文件。

问题:有没有办法在ZipArchive使用’stream’创建’entry’,这样我就可以直接在zip中输入文件的内容?

我不想先保存文件,创建zip(从保存文件的路径),然后删除单个文件。

这里, attachmentFilesIEnumerable

 using (var ms = new MemoryStream()) { using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true)) { foreach (var attachment in attachmentFiles) { zipArchive.CreateEntryFromFile(Path.GetFullPath(attachment.FileName), Path.GetFileName(attachment.FileName), CompressionLevel.Fastest); } } ... } 

是的,您可以使用ZipArchive.CreateEntry方法执行此操作,因为@AngeloReis在注释中指出,并在此处描述了稍微不同的问题。

您的代码将如下所示:

 using (var ms = new MemoryStream()) { using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true)) { foreach (var attachment in attachmentFiles) { var entry = zipArchive.CreateEntry(attachment.FileName, CompressionLevel.Fastest); using (var entryStream = entry.Open()) { attachment.InputStream.CopyTo(entryStream); } } } ... } 

首先感谢@Alex的完美答案。
此外,您还需要从文件系统中读取:

 using (var ms = new MemoryStream()) { using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true)) { foreach (var file in filesAddress) { zipArchive.CreateEntryFromFile(file, Path.GetFileName(file)); } } ... } 

System.IO.Compression.ZipFileExtensions的帮助下