任务: 我想在运行中创建包含一定数量Excel文件的zip存档。 Excel文件也是动态创建的。以下是简单方法的一部分:
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);
}
问题:
我在尝试解压缩生成的存档时遇到错误“存档已损坏或格式错误”。在存档中,我看到Crc32 is 00000000
表示evry文件。
//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();
}
问题:在被问到这个问题之前,我已经尝试了很多压缩和Crc32设置的选项。另外我注意到在创建一个Excel文件时没有错误。否则在存档中我看到Crc32对于evry文件是00000000而我在尝试解压缩存档时遇到错误“存档已损坏或格式错误”。 SharpZipLib的这种行为的原因是什么?