Ionic.Zip ArgumentException (An item with the same key has already been added)

3.3k views Asked by At

I'm using Ionic Zip to zip all folders in a specific folder excluding the backup folder (which created backups goes).

This is my code:

ZipFile zip = new ZipFile();
string mainpath = HttpContext.Current.Server.MapPath("~/");
Directory.GetDirectories(mainpath).Where(d=> !d.ToLower().EndsWith("backup")).ToList()
.ForEach(d=> zip.AddDirectory(d));

but after adding some directories, I'm getting the following error:

An item with the same key has already been added.

How is it possible? How can possibly be duplicate names in the folder list in the same parent folder?

1

There are 1 answers

0
Ashkan Mobayen Khiabani On BEST ANSWER

As I inspected the exception, it seems that it adds the list of all files to be archived in a dictionary.

I don't know what it uses as a key that can cause this error (might be using the file name as the key and having same name in two different folders can cause it).

Solution: However I found out that AddDirectory and AddFiles has another overload that accepts directory path in archive. giving each of the directories a unique path in archive solved the problem. in my case I used:

    string mainpath = HttpContext.Current.Server.MapPath("~/");
    Directory.GetDirectories(mainpath).Where(d=> !d.ToLower().EndsWith("backup")).ToList()
.ForEach(d=> zip.AddDirectory(d, d.Substring(mainpath.Length)));