Frage

I've been having a bit of a problem lately. I've been trying to extract one zip file into a memory stream and then from that stream, use the updateEntry() method to add it to the destination zip file.

The problem is, when the file in the stream is being put into the destination zip, it works if the file is not already in the zip. If there is a file with the same name, it does not overwrite correctly. It says on the dotnetzip docs that this method will overwrite files that are present in the zip with the same name but it does not seem to work. It will write correctly but when I go to check the zip, the files that are supposed to be overwritten have a compressed byte size of 0 meaning something went wrong.

I'm attaching my code below to show you what I'm doing:

ZipFile zipnew = new ZipFile(forgeFile);
ZipFile zipold = new ZipFile(zFile);

using(zipnew) {
    foreach(ZipEntry zenew in zipnew) {
        percent = (current / zipnew.Count) * 100;
        string flna = zenew.FileName;
        var fstream = new MemoryStream();

        zenew.Extract(fstream);
        fstream.Seek(0, SeekOrigin.Begin);

        using(zipold) {
            var zn = zipold.UpdateEntry(flna, fstream);
            zipold.Save();
            fstream.Dispose();
        }
        current++;
    }
    zipnew.Dispose();
}
War es hilfreich?

Lösung

Although it might be a bit slow, I found a solution by manually deleting and adding in the file. I'll leave the code here in case anyone else comes across this problem.

ZipFile zipnew = new ZipFile(forgeFile);
ZipFile zipold = new ZipFile(zFile);

using(zipnew) {
    // Loop through each entry in the zip file
    foreach(ZipEntry zenew in zipnew) {
        string flna = zenew.FileName;

        // Create a new memory stream for extracted files
        var ms = new MemoryStream();


        // Extract entry into the memory stream
        zenew.Extract(ms);
        ms.Seek(0, SeekOrigin.Begin); // Rewind the memory stream

        using(zipold) {
            // Remove existing entry first
            try {
                zipold.RemoveEntry(flna);
                zipold.Save();
            }
            catch (System.Exception ex) {} // Ignore if there is nothing found

            // Add in the new entry
            var zn = zipold.AddEntry(flna, ms);
            zipold.Save(); // Save the zip file with the newly added file
            ms.Dispose(); // Dispose of the stream so resources are released
        }
    }
    zipnew.Dispose(); // Close the zip file
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top