如何更新 ZIP 存档中的每个文件?

How can I update each file in a ZIP archive?

尝试以下操作时出现错误 "Collection was modified; enumeration operation may not execute."。我如何遍历 Zip 条目并更新它们?

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

您无法在枚举集合时更新集合。

您可以改为转换为 for 循环。

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

您可能会发现阅读 Enumerators 上的 API 参考资料很有帮助。

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