作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
是否有可能从内存中(而不是实际在磁盘上)的文件创建 ZipArchive。
以下是用例:IEnumerable<HttpPostedFileBase>
中收到多个文件多变的。我想使用 ZipArchive
将所有这些文件压缩在一起.问题是 ZipArchive
只允许 CreateEntryFromFile
,它需要文件的路径,因为我只是在内存中有文件。
问题:有没有办法使用“流”在 ZipArchive
中创建“条目”? ,以便我可以直接将文件内容放入 zip 中?
我不想先保存文件、创建 zip(从保存文件的路径)然后删除单个文件。
在这里,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 在评论中指出的那样,并描述了 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/
我是一名优秀的程序员,十分优秀!