2013-03-12 26 views
3

最近我一直有點問題。我一直試圖將一個zip文件提取到內存流中,然後從該流中使用updateEntry()方法將其添加到目標zip文件。使用dotnetzip的updateEntry()方法不會正確覆蓋文件

問題是,當流中的文件被放入目標zip文件時,如果該文件尚未在zip文件中,則該文件可以正常工作。如果有一個具有相同名稱的文件,它不會正確覆蓋。它在dotnetzip文檔中說,這種方法會覆蓋壓縮文件中的同名文件,但似乎不起作用。它會正確寫入,但當我去檢查壓縮文件時,應該被覆蓋的文件的壓縮字節大小爲0,這意味着出錯了。

我附上我的代碼下面給你看我在做什麼:

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(); 
} 

回答

4

雖然它可能是一個有點慢,我發現了一個解決方案通過手動刪除,並在文件中添加。如果有其他人遇到此問題,我會將代碼留在此處。

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 
}