简体   繁体   English

覆盖 zip 文件中的条目

[英]Overwrite entry in zip file

I'm having trouble, I got this code:我遇到了麻烦,我得到了这个代码:

DirectoryInfo di = new DirectoryInfo(dir);
FileInfo[] rgFiles = di.GetFiles();
DirectoryInfo[] d = di.GetDirectories();
if(rgFiles != null && d != null) {
foreach (FileInfo fi in rgFiles)
{
    foreach (DirectoryInfo dii in d)
    {
        using (ZipFile zip = ZipFile.Read(locateZipFile()))
        {

            zip.AddFile(fi.FullName, "");

            zip.AddDirectory(dii.FullName,dii.Name);
            toolStripStatusLabel1.Text = "Inserting " + fi.Name;
            toolStripStatusLabel1.Text = "Inserting " + dii.Name + " and all of it's contents";

            MessageBox.Show("Inserted the file " + fi.Name);
            MessageBox.Show("Inserted the folder " + dii.Name + " and all contents in it.");
            zip.Save();

        }
    }
}

Everything works great, but when I'm trying to add a file that is named the same in the zip, it does not overwrite it, which i want it to.. Any ideas on how i can do that?一切都很好,但是当我尝试添加一个在 zip 中命名相同的文件时,它不会覆盖它,这是我想要的......关于我如何做到这一点的任何想法? thanks.谢谢。

You can use the UpdateFile method.您可以使用UpdateFile方法。

zip.UpdateFile(fi.FullName, "");

This method adds a file to a zip archive, or, if the file already exists in the zip archive, this method Updates the content of that given filename in the zip archive.此方法将文件添加到 zip 存档,或者,如果该文件已存在于 zip 存档中,则此方法更新 zip 存档中给定文件名的内容。 The UpdateFile method might more accurately be called "AddOrUpdateFile". UpdateFile 方法可能更准确地称为“AddOrUpdateFile”。

Upon success, there is no way for the application to learn whether the file was added versus updated.成功后,应用程序无法了解文件是添加还是更新。

Before the line行前

zip.AddFile(fi.FullName, "");

you must test if the name already exists in entries.您必须测试该名称是否已存在于条目中。 If yes, remove it and then insert it again.如果是,请将其移除,然后再次插入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM