I've been playing with the new (better? improved?) support for zip files in .NET 4.5 and ran into some issues recently where I couldn't read the contents of an archive I had created or when I added entries to an archive, they never appeared.



When I would create the archive using the ZipFile.CreateFromDirectory() method, everything worked just fine:

ZipArchive archive = ZipFile.CreateFromDirectory("C:\\PathToSomeDirectorySomewhere",
                                                 "NameOfMyAwesomeNewZipFile.zip");

However, when I tried to add files to it, they would never show up:

ZipArchiveEntry entry = archive.CreateEntryFromFile("PathToSomeOtherNewFile",
                                                    "NameOfNewFile.txt");

So I decided to try creating the zip file manually, thinking that maybe there was an issue with modifying a CreateFromDirectory() archive:

ZipArchive archive = ZipFile.Open("C:\PathToMyNewBetterZipFile.zip",
                                  ZipArchiveMode.Create);

Now, when I opened it with WinRAR (or 7Zip, or <insert tool of choice>), I received some errors when trying to actually view the contents of entries.

At this point, I'm thinking that I'm missing something that actually closes the file or writes it to disk; it turns out that I was. I added archive.Dispose() to the end of the file and everything started working. Lazy programmer me. After re-reading the example I had been using (from this MSDN Magazine article: http://msdn.microsoft.com/en-us/magazine/jj133817.aspx), I realized that I had missed a critical difference between the example and my implementation:

using (ZipArchive archive = ZipFile.Open(...)
{
   //Stuff goes here...
}

This pretty much took care of the issue entirely - just make sure that the ZipArchive is disposed when you're done with it.