3

I have tried zipping 70 pdf documents but ended up having a System.OutOfMemoryException. Please look into the following code and let me know whats wrong with it. Please note that I have posted issue on GitHub as well.

public byte[] DownloadPaperList()
    {
        try
        {
            PaperDAO paperDAO = new PaperDAO();
            List<PaperModel> papers = paperDAO.GetPaperListByPaperIds(paperIDs);                                
            using (MemoryStream outputMemoryStream = new MemoryStream())
            {
                using (var zipOutputStream = new ZipOutputStream(outputMemoryStream))
                {
                    papers = papers.OrderBy(x => x.Order).ToList();                        
                    foreach (PaperModel paper in papers)
                    {
                        byte[] decryptedPaper
                         = CryptoServices.DecryptFile(paper.FileData, paperDAO.GenerateCloseOpenFile(paper, string.Empty), paper.SEVersion);

                        ZipEntry zipFileEntry = new ZipEntry(paper.DocName + ".pdf")
                            {
                                Size = decryptedPaper.Length
                            };

                        zipOutputStream.SetLevel(3);
                        zipOutputStream.PutNextEntry(zipFileEntry); //EXCEPTION THROWS HERE!!!

                        StreamUtils.Copy(new MemoryStream(decryptedPaper), zipOutputStream, new byte[4096]);
                    }
                    zipOutputStream.CloseEntry();
                    // Stop ZipStream.Dispose() from also Closing the underlying stream.
                    zipOutputStream.IsStreamOwner = false;
                    outputMemoryStream.Position = 0;
                }
                return outputMemoryStream.ToArray();
            }
        }            
        catch (Exception)
        {
            throw;
        }
    }
SurenSaluka
  • 1,534
  • 3
  • 18
  • 36
  • 1
    I think this answer will help you brother https://stackoverflow.com/questions/26417823/c-sharp-outofmemoryexception-creating-zipoutputstream-using-sharpziplib – Alpesh Vaghela Jan 13 '20 at 12:01
  • 1
    You are not using streams correctly. Try to find a way to stream your zip file into an actual file or place, that isn't system memory. Your zip file looks to be exhausting your system memory. – InDieTasten Jan 13 '20 at 12:01
  • Well you are streaming to memory instead of disk... – DavidG Jan 13 '20 at 12:03

0 Answers0