Search code examples
c#dotnetzip

Usage of DotNetZip


I am using DotNetZip library to compress files. my code is given below

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

Now when the Archive.zip is created, there are folders created in the archive with the same name(e.g Data, ProgramFiles etc)for files in which they were stored.

My target is to compress all the files in Archive.zip without any folder in the archive. how can I achieve it?


Solution

  • The AddFiles has an overload to flatten the directory structure in the zip archive

    public void AddFiles(
        IEnumerable<string> fileNames,
        bool preserveDirHierarchy,
        string directoryPathInArchive
    )
    

    http://dotnetzip.herobo.com/DNZHelp/html/c64e89d3-2f1f-2886-16bc-291746b46718.htm

    zip.AddFiles(filenames, false, "files");
    

    The second parameter preserveDirHierarchy can be passed as false to have all files in the root of the zip archive. Be careful that you do not have files with the same name when doing this. It will throw an Exception for duplicate file names.