I try to create a zip file in memory with c#, but the result is a zip file with corrupted files inside it. All file to zip are in a database. I store the bytes. The files are PDF. my code is the following
//[extract bytes and file name for every file]
using (var zipArchiveMemoryStream = new MemoryStream())
{
using (var zipArchive = new ZipArchive(zipArchiveMemoryStream,
ZipArchiveMode.Create, true))
{
foreach (var file in fileData)
{
var zipEntry = zipArchive.CreateEntry(file.FileName);
using (var entryStream = zipEntry.Open())
{
using (var tmpMemory = new MemoryStream(file.Bytes))
{
tmpMemory.CopyTo(entryStream);
};
}
}
}
zipArchiveMemoryStream.Position = 0;
result = zipArchiveMemoryStream.GetBuffer();
//[download zip file]
Thanks in advance for your support
SOLUTION BY TONIGNO: the problem was that i use GetBuffer(); instead ToArray();
using (var zipArchiveMemoryStream = new MemoryStream())
{
using (var zipArchive = new ZipArchive(zipArchiveMemoryStream, ZipArchiveMode.Create, true))
{
foreach (var file in fileData)
{
var zipEntry = zipArchive.CreateEntry(file.FileName);
using (var entryStream = zipEntry.Open())
{
using (var tmpMemory = new MemoryStream(file.Bytes))
{
tmpMemory.CopyTo(entryStream);
};
}
}
}
zipArchiveMemoryStream.Seek(0, SeekOrigin.Begin);
result = zipArchiveMemoryStream.ToArray();
}
return result;
Try to take a look to this: Creating a ZIP Archive in Memory Using System.IO.Compression. The solution is this:
It explains how to create the zip archive in memory and contains a link to another useful article that explains the use of the leaveOpen argument to prevent the closing of the stream: ZipArchive creates invalid ZIP file that contains this solution:
I hope it's helpful!
EDIT
Instead of
zipArchiveMemoryStream.GetBuffer()
usezipArchiveMemoryStream.ToArray()