-2

I am having a hard time creating a ZipArchive successfully on Asp.net core MVC. I have an excel file generated with data that works and I need to put in an archive. This is what I've done so far

        public FileResult ExportGoodsReceiptData()
        {
            var records = _salesService.GetAllReceipts();
            var lineRecords = _salesService.GetAllReceiptLines();
            var result = _salesService.ExportGoodsReceiptData(records);
            var lineResult = _salesService.ExportGoodsReceiptLineData(lineRecords);

            byte[] resultArr = StreamToByteArray(result);
            byte[] lineResultArr = StreamToByteArray(lineResult);

            using(MemoryStream stream = new MemoryStream())
            {
                using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
                {
                    var zipArchiveEntry = archive.CreateEntry("GoodsReceipts.csv", CompressionLevel.Fastest);
                    using (var zipStream = zipArchiveEntry.Open())
                    using (var resultCom = new MemoryStream(resultArr))
                    {
                        resultCom.CopyTo(zipStream);
                    }
                }

                return new FileStreamResult(stream, "application/zip") { FileDownloadName = "GoodsReceiptsArchive.zip" };
            }
        }

When I run it, I get the zipfile, but can't open it. It throws error stating that it may have been damaged. I debugged the code to notice that one of the properties (length property) throws an invalidOperation exception. My approach looks identical to most samples I found online. Don't know how else to solve this. Please help.

H H
  • 263,252
  • 30
  • 330
  • 514
Kacey Ezerioha
  • 1,068
  • 4
  • 22
  • 46

1 Answers1

0

Your problem is that you're disposing of your memory stream before you return it. Remove this using:

using(MemoryStream stream = new MemoryStream())

Replace it with:

var stream = new MemoryStream();

Asp.Net MVC will automatically dispose of the stream for you.