Search code examples
c#zipsystem.io.compressionc#-ziparchive

How can I update each file in a ZIP archive?


When trying the following I get the error "Collection was modified; enumeration operation may not execute.". How can I loop through Zip entries and update them?

using (ZipArchive archive = ZipFile.Open(@"c:\file.zip",ZipArchiveMode.Update))
{
    foreach (ZipArchiveEntry entry in archive.Entries)
    {
        archive.CreateEntryFromFile(@"c:\file.txt", entry.FullName);
    }
}

Solution

  • You can't update a collection whilst enumerating through it.

    You could convert to a for loop instead.

    for (int i = 0; i < archive.Entries.Count; i++)
    {
        archive.CreateEntryFromFile(@"c:\file.txt", archive.Entries[i].FullName);
    }
    

    You may find it helpful to have a read of the API reference on Enumerators.

    "Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection."