3

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

         }
   }
Md Aslam
  • 1,228
  • 8
  • 27
  • 61

1 Answers1

9

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);
        }
    }
}
stukselbax
  • 5,855
  • 3
  • 32
  • 54
  • Thank you for your help and quick response, but the small concern here is the data of the zip file is not opening properly. It shows "we don't support this file format" . So the variable "s" should be outside of "using" keyword? Please help me onthis – Md Aslam Aug 07 '18 at 05:32
  • Have you tried to search for error? Where exception is thrown? Have you closed the zip archive before looking at? – stukselbax Aug 07 '18 at 05:38
  • No, I tried your code and there is no exception thrown. That means I got the final output file as a zip. But I am not able to open a file from the zip file. If I remove your code that using "(var s =)...." then I am able to open the files inside zip. – Md Aslam Aug 07 '18 at 05:42
  • I got the problem, but don't know the solution please help me fore this. Problem: If I use the memorystream as a list, then the file format is not working properly. I don't know why, but if I mention like (msList[i].Position = 0;) its not working properly. So could you please help me with this? @ Stukselbax – Md Aslam Aug 07 '18 at 06:15
  • @MdAslam you should try it out yourself first. If you have trouble and didn't find the solution online, you should open new question. – stukselbax Aug 08 '18 at 12:55
  • Thank you. One small clarification from my above question that, I missed using on the opened stream right, If we use "using" also same only right then how here the stream object closed the created entry. So what is the difference between "using(..){}" and without "using" ? – Md Aslam Aug 09 '18 at 04:57