Hi
Task:
I want to create zip archives on the fly containing a certain number of Excel files. Excel files are created from the database also on the fly.
Problem:
I get an error when trying to unzip the resulting archive "Archive is damaged or has the wrong format". In archive i see that Crc32 is 00000000 for evry files. Also a have no errors when only one file is archiv.
Code:
//load excel files to archive
using (var stream = new MemoryStream())
{
using (var zipPackage = new ZipHelper(stream))
{
foreach (var dt in res)
{
MemoryStream ms = new MemoryStream();
XLWorkbook wb = new XLWorkbook();
wb.Worksheets.Add(dt);
wb.SaveAs(ms);
zipPackage.Add(ms,
string.Format(CultureInfo.InvariantCulture, "{0}.xlsx",
string.Format(CultureInfo.InvariantCulture, dt.TableName)));
ms.Flush();
ms.Close();
}
}
stream.Flush();
LoadZipToResponse(stream);
}
//Add mehod
public ZipHelper Add(MemoryStream ms, string cleanName)
{
var zipEntry = new ZipEntry(cleanName)
{
DateTime = DateTime.Now,
Size = ms.Length
};
zipEntry.CompressionMethod = CompressionMethod.Stored;
_crc.Reset();
_crc.Update(ms.ToArray());
zipEntry.Crc = _crc.Value;
_zipStream.PutNextEntry(zipEntry);
_zipStream.Write(ms.GetBuffer(), 0, (int)ms.Length);
_zipStream.CloseEntry();
return this;
}
//LoadZipToResponse
private void LoadZipToResponse(MemoryStream stream)
{
Response.ContentType = "application/zip";
Response.AppendHeader("content-disposition", "attachment; filename=\"" + "DataExport.zip" + "\"");
Response.CacheControl = "Private";
Response.Cache.SetExpires(DateTime.Now.AddMinutes(5));
Page.Response.BinaryWrite(stream.GetBuffer());
stream.Close();
Response.Flush();
Response.End();
}