How do I add files to an existing zip archive
Asked Answered
S

3

31

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

Stinkhorn answered 11/3, 2014 at 23:59 Comment(2)
This question is not specific to sharpziplib, so I have reopened it.Lingcod
Possible duplicate of Add Files Into Existing ZipImmotile
L
36

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("========================");
       }
   }
}
Lingcod answered 12/3, 2014 at 0:6 Comment(7)
I am trying your suggestion Lord Takkera but I see a "snag". I am using the below: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.IO.Compression; using System.Diagnostics; The "ZipArchive" has a red underline.Stinkhorn
The ZipArchive class was added in .NET 4.5.Poland
Make sure you have a project reference to System.IO.Compression, and that you are using .NET 4.5 (you should since you are on VS 2012).Lingcod
Any chance you could elaborate on 'You could probably even find a way to just copy it in'? That is exactly what I need but I can't get it to work.Splenetic
@MikeDymond You would use the CreateEntryFromFile method: msdn.microsoft.com/en-us/library/hh485720(v=vs.110).aspx If you wanted to post a new quesiton, I'd be happy to provide a code sample. I don't feel that this use case is all that important to this question.Lingcod
@Lingcod Thanks for that. I had tried that before but hadn't realised that CreateEntryFromFile is in a DIFFERENT assembly to the ZipArchive object. Once I added that reference it worked no problem.Splenetic
Also, check out ZipFileExtensions.CreateEntryFromFileOstensive
P
36

For creating, extracting, and opening zip archives, we can use ZipFile Class with reference: System.IO.Compression.FileSystem. For .NET 4.5.2 and below, we also need to add reference: System.IO.Compression. Here's the method for adding files to zip:

    public static void AddFilesToZip(string zipPath, string[] files)
    {
        if (files == null || files.Length == 0)
        {
            return;
        }

        using (var zipArchive = ZipFile.Open(zipPath, ZipArchiveMode.Update))
        {
            foreach (var file in files)
            {
                var fileInfo = new FileInfo(file);
                zipArchive.CreateEntryFromFile(fileInfo.FullName,  fileInfo.Name);
            }
        }
    }
Porky answered 5/12, 2017 at 5:40 Comment(5)
Thank you for this answer which I agree is much cleaner and neater. However, I struggled a little bit at first until I realised this answer requires a reference System.IO.Compression.Filesystem (not just System.IO.Compression). Thanks.Forlorn
@FeiyuZhou, could you suggest how to add a folder and then the files.Karalee
@BinoyCherian you can modify the code in foreach to support folder by using CreateEntryFromFolder methodPorky
Don't be confused, if you don't find the CreateEntryFromFile at the documentation of the ZipFile class. This method, and two other useful ones (ExtractToDirectory and ExtractToFile) are defined namely as extension methods in the ZipFileExtensions class.Antitoxin
For something like CreateEntryFromFolder to work we need to add Val's extension class here. It implements a CreateEntryFromDirectory method and work recursively just fine..Rheumy
B
7

The easiest way is to get DotNetZip at http://dotnetzip.codeplex.com/

Adding files can be as easy as

String[] filenames = { @"ReadMe.txt",
                       @"c:\data\collection.csv" ,
                       @"c:\reports\AnnualSummary.pdf"
                     } ;
using ( ZipFile zip = new ZipFile() )
{
  zip.AddFiles(filenames);
  zip.Save("Archive.zip");
}

Other sorts of updates are just as trivial:

using (ZipFile zip = ZipFile.Read("ExistingArchive.zip"))
{

  // update an existing item in the zip file
  zip.UpdateItem("Portfolio.doc"); 

  // remove an item from the zip file
  zip["OldData.txt"].RemoveEntry();

  // rename an item in the zip file
  zip["Internationalization.doc"].FileName = "i18n.doc";

  // add a comment to the archive
  zip.Comment = "This zip archive was updated " + System.DateTime.ToString("G");

  zip.Save();
}

Edited To Note: DotNetZip used to live at Codeplex. Codeplex has been shut down. The old archive is still [available at Codeplex][1]. It looks like the code has migrated to Github:


Brooklyn answered 12/3, 2014 at 0:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.