gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 07:54:44 24 4
gpt4 key购买 nike

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

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

问题:有没有办法使用“流”在 ZipArchive 中创建“条目”? ,以便我可以直接将文件内容放入 zip 中?

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

在这里,attachmentFilesIEnumerable<HttpPostedFileBase>

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 在评论中指出的那样,并描述了 here对于一个稍微不同的问题。

您的代码将如下所示:

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);
}
}
}
...
}

关于c# - 如何在 C# 中从内存中的文件创建 ZipArchive?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29647570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com