Search code examples
c#memorystreamc#-ziparchive

How to close the created entry from ziparchive


I have written a method as below to bind multiple Memorystream to ziparchive. The code is working for one stream, but if I add a multiple stream by iterating, then it shows following error in 2nd line from for loop.

 System.IO.IOException: 'Entries cannot be created 
 while previously created entries are still open.' 

My Code,

 using (var zip = new ZipArchive(outputStream, ZipArchiveMode.Create, 
 leaveOpen: false))
  {

        for (int i = 0; i < msList.Count; i++)
        {
          msList[i].Position = 0;
         var createenter = zip.CreateEntry("123"+i+".jpg", 
         CompressionLevel.Optimal);
         msList[i].CopyTo(createenter.Open());

         }
   }

Solution

  • You have probably missed using on the opened Stream?

     using (var zip = new ZipArchive(outputStream, ZipArchiveMode.Create, leaveOpen: false))
     {
        for (int i = 0; i < msList.Count; i++)
        {
            msList[i].Position = 0;
            var createenter = zip.CreateEntry("123"+i+".jpg", 
            CompressionLevel.Optimal);
            using (var s = createenter.Open())
            {
                msList[i].CopyTo(s);
            }
        }
    }