首頁 > 後端開發 > C++ > 如何使用 C# 成功建立記憶體中 ZIP 檔案並避免「無效 ZIP」錯誤?

如何使用 C# 成功建立記憶體中 ZIP 檔案並避免「無效 ZIP」錯誤?

Barbara Streisand
發布: 2025-01-07 00:33:46
原創
304 人瀏覽過

How to Successfully Create an In-Memory ZIP Archive Using C# and Avoid the

使用System.IO.Compression 在記憶體中建立ZIP 檔案:克服無效的ZIP 錯誤

嘗試在記憶體中建立ZIP 錯誤

嘗試在記憶體中建立ZIP 檔案時使用MemoryStream 儲存記憶體時,您可能會遇到建立存檔但缺少所需內容的問題。出現此問題的原因是需要將最終位元組(例如校驗和)寫入存檔才能完成。
using (var memoryStream = new MemoryStream())
{
   using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
   {
      var demoFile = archive.CreateEntry("foo.txt");

      using (var entryStream = demoFile.Open())
      using (var streamWriter = new StreamWriter(entryStream))
      {
         streamWriter.Write("Bar!");
      }
   }

   using (var fileStream = new FileStream(@"C:\Temp\test.zip", FileMode.Create))
   {
      memoryStream.Seek(0, SeekOrigin.Begin);
      memoryStream.CopyTo(fileStream);
   }
}
登入後複製

要解決此問題,您可以使用以下修改後的程式碼:

這裡的關鍵差異是 ZipArchive 建構函式中的第三個參數,該參數設為 true。此參數指示可以在不關閉基礎流的情況下處置 ZipArchive。這允許您在建立存檔後重複使用 MemoryStream。 透過使用修改後的程式碼,即使使用 MemoryStream,您也可以在記憶體中成功建立具有所需內容的 ZIP 檔案。這種靈活性使您可以在各種場景下操作檔案,而無需中間文件處理。

以上是如何使用 C# 成功建立記憶體中 ZIP 檔案並避免「無效 ZIP」錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板