我有一堆字节数组形式的Jpg图像。我想将这些添加到zip文件,将zip文件转换为字节数组,并将其传递到其他地方。在方法中,我有这个代码:
var response = //some response object that will hold a byte array
using (var ms = new MemoryStream())
{
using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true))
{
var i = 1;
foreach (var image in images) // some collection that holds byte arrays.
{
var entry = zipArchive.CreateEntry(i + ".jpg");
using (var entryStream = entry.Open())
using (var compressStream = new MemoryStream(photo.ImageOriginal))
{
compressStream.CopyTo(entryStream);
}
i++;
}
response.ZipFile = ms.ToArray();
}
using (var fs = new FileStream(@"C:\Users\MyName\Desktop\image.zip", FileMode.Create))
{
ms.Position = 0;
ms.CopyTo(fs);
}
}
return response;
现在,我已经在底部附近添加了一个文件流,立即将其写入zipfile以进行测试。这有效,我得到一个包含一个或多个图像的zip文件在我的桌面上。但是:response.ZipFile
无法以相同的方式成为有效的zip文件。我试过这个:
using (var ms2 = new MemoryStream(response.ZipFile))
using (var fs = new FileStream(@"C:\Users\Bara\Desktop\image.zip", FileMode.Create))
{
ms2.Position = 0;
ms2.CopyTo(fs);
}
但是这会创建一个无法打开的zip文件。
我尝试做的事情:将response.ZipFile
转换为可以再次转换为工作zipfile的数组。我在这段代码中做错了什么?
答案 0 :(得分:2)
您如何知道ZipArchive
Dispose
没有向基础流写更多内容?
您应该在处置ZipArchive
:
response.ZipFile = ms.ToArray();
完整代码:
var response = //some response object that will hold a byte array
using (var ms = new MemoryStream())
{
using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true))
{
var i = 1;
foreach (var image in images) // some collection that holds byte arrays.
{
var entry = zipArchive.CreateEntry(i + ".jpg");
using (var entryStream = entry.Open())
using (var compressStream = new MemoryStream(photo.ImageOriginal))
{
compressStream.CopyTo(entryStream);
}
i++;
}
}
response.ZipFile = ms.ToArray();
}
return response;