0

Task: I want to create zip archives on the fly that containing a certain number of Excel files. Excel files are created from the database also on the fly. Here is the part of the simple method:

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);
            }

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.

//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();
        }

Question: Before asked this question I've tried a lot of options of compression and Crc32 settings.Also I'm notice there are no errors when creating only one Excel file. Otherwise In archive i see that Crc32 is 00000000 for evry files and i'm get an error when trying to unzip the archive "Archive is damaged or has the wrong format". What is the reason for this behavior of the SharpZipLib?

0 Answers0