Search code examples
c#dotnetzip

Add Files Into Existing Zip


I can successfully extract files from a zip folder into a folder, but I am not quite sure how to take those files and add them into an existing zip file. I extract them into a directory onto the desktop called "mod", and then I need to add them to another zip file. Help? Here is my extraction code-

ZipFile zip = ZipFile.Read(myZip);
zip.ExtractAll(outputDirectory,ExtractExistingFileAction.OverwriteSilently);

Help is appreciated, thank you.


Solution

  • Try giving this a try, once you extract the files from the source zip, you will need to read the destination zip file into a ZipFile object you can then use the AddFiles method to add your source files to the destination file, then save it.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text; 
    using Ionic.Zip;
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string myZip = @"C:\temp\test.zip";
                string myOtherZip = @"C:\temp\anotherZip.zip";
                string outputDirectory = @"C:\ZipTest";
    
                using (ZipFile zip = ZipFile.Read(myZip))
                {
                    zip.ExtractAll(outputDirectory, ExtractExistingFileAction.OverwriteSilently);
                }
    
                using (ZipFile zipDest = ZipFile.Read(myOtherZip))
                {
                    //zipDest.AddFiles(System.IO.Directory.EnumerateFiles(outputDirectory)); //This will add them as a directory
                    zipDest.AddFiles((System.IO.Directory.EnumerateFiles(outputDirectory)),false,""); //This will add the files to the root
                    zipDest.Save();
                }
            }
        }
    }
    

    Modified Method for adding a Directory to the ZipFile ( This will work for a single sub directory level )

    using (ZipFile zipDest = ZipFile.Read(myOtherZip))
    {
        foreach (var dir in System.IO.Directory.GetDirectories(outputDirectory))
        {
            zipDest.AddFiles((System.IO.Directory.EnumerateFiles(dir)),false,outputDirectory ); //directory to the root
        }
        zipDest.AddFiles((System.IO.Directory.EnumerateFiles(outputDirectory)),false,""); //This will add the files to the root
        zipDest.Save();
    }
    

    Method for deleting files from a Zip Directory

    List<string> files = zipDest.EntryFileNames.ToList<string>(); // Get List of all the archives files
    for (int i = 0; i < files.Count; i++)
    {
        if(files[i].Contains("ZipTest")) //replace the directory you wish to delete files from here
            zipDest.RemoveEntry(files[i]);
    }