How do I add files to an existing zip archive

user3408397 picture user3408397 · Mar 12, 2014 · Viewed 41k times · Source

How can I add some file (almost always a single .csv file) to an existing zip file?

Answer

BradleyDotNET picture BradleyDotNET · Mar 12, 2014

Since you are in .NET 4.5, you can use the ZipArchive (System.IO.Compression) class to achieve this. Here is the MSDN documentation: (MSDN).

Here is their example, it just writes text, but you could read in a .csv file and write it out to your new file. To just copy the file in, you would use CreateFileFromEntry, which is an extension method for ZipArchive.

using (FileStream zipToOpen = new FileStream(@"c:\users\exampleuser\release.zip", FileMode.Open))
{
   using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
   {
       ZipArchiveEntry readmeEntry = archive.CreateEntry("Readme.txt");
       using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
       {
           writer.WriteLine("Information about this package.");
           writer.WriteLine("========================");
       }
   }
}