ZipFile.Save(Stream) - DO NOT read from a stream, then try to save to the same stream: Question

Jul 14, 2012 at 4:14 AM

Hey everyone,

First off, thanks for the awesome library! Seriously good stuff! I am using the latest version of the library,

I have a question about Streams and the ZipFile.Save() overloads. Recently, I ran into problems attempting to update the contents of an existing zip file. In my scenario, the contents being updated were several layers deep within nested zip files. To make a long story short, my approach was to open a Stream to each nested zip file (and the root zip file) and use ZipFile.Read(Stream) to modify the contents of each parent zip file with the modified child archive, all the way back to the root file. However, when I tried to save (replace) the original root zip file, I was getting an exception stating that the zip file I was currently trying to modify was being used by another process.

Searching through the documentation, I found the following page on ZipFile.Save(Stream):

Specifically, I noticed the example code at the bottom of this page which states you should not read from a stream, then try to save to the same stream. Even though I was not using this overload of Save, I figured maybe since I still had a Stream of the root zip file open that was why I was getting that exception. Come to find out, I had a bug in my logic where I wasn't closing all of the Streams properly, and now my original implementation seems to be working fine. It turns out my implementation is very similar to the example "pitfall" code referenced in the above documentation:


using (var inputStream = new FileStream(filename, FileMode.Open))
  using (var zip = Ionic.Zip.ZipFile.Read(inputStream))
    zip.AddEntry("Name1.txt", "this is the content");
    zip.Save(filename);  // Is this valid??

The only difference is that I use the ZipFile.Save overload that takes in a file path, not the input stream. Is there anything wrong with this approach, or does this seem valid to everyone?  

Thanks for your insight,