如何从C#内存中的文件创建ZipArchive? [英] How to create ZipArchive from files in memory in C#?
问题描述
是否可以通过内存中的文件(而不是磁盘上的文件)创建ZipArchive。
Is it somehow possible to create a ZipArchive from the file(s) in memory (and not actually on the disk).
以下是用法情况:
在 IEnumerable< HttpPostedFileBase>
变量中接收到多个文件。我想使用 ZipArchive
将所有这些文件压缩在一起。问题是 ZipArchive
仅允许 CreateEntryFromFile
,该文件需要文件的路径,因为我只有文件
Following is the use case:
Multiple files are received in an IEnumerable<HttpPostedFileBase>
variable. I want to zip all these files together using ZipArchive
. The problem is that ZipArchive
only allows CreateEntryFromFile
, which expects a path to the file, where as I just have the files in memory.
问题:
是否可以使用流在<$中创建条目 c $ c> ZipArchive ,这样我就可以直接在zip文件中放入文件内容了吗?
Question:
Is there a way to use a 'stream' to create the 'entry' in ZipArchive
, so that I can directly put in the file's contents in the zip?
我不想先保存文件,(从保存的文件的路径创建zip),然后删除单个文件。
I don't want to first save the files, create the zip (from the saved files' paths) and then delete the individual files.
此处, attachmentFiles
是 IEnumerable< 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在评论中指出的,并在此处,因为问题稍有不同。
Yes, you can do this, using the ZipArchive.CreateEntry method, as @AngeloReis pointed out in the comments, and described here for a slightly different problem.
您的代码将如下所示:
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#内存中的文件创建ZipArchive?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!