2017-10-22 124 views
1

我試圖將一堆文件添加到C#中的zipfile,但它似乎不能正常工作。C#似乎無法正確添加圖像到ziparchive

using (var memoryStream = new MemoryStream()) 
{ 
    using (var zip = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) 
    { 
     for (int i = 0; i < kaart_data.GetLength(0); i++) 
     { 
      Image img = array[i]; 

      var file = zip.CreateEntry(i + ".bmp"); 
      using (var stream = new MemoryStream()) 
      { 
       img.Save(stream, ImageFormat.Bmp); 
       using (var entryStream = file.Open()) 
       { 
        stream.CopyTo(entryStream); 
       } 
      } 
     } 
    } 

    //saves the archive to disk 
    using (var fileStream = new FileStream(@"C:\Temp\test.zip", FileMode.Create)) 
    { 
     memoryStream.Seek(0, SeekOrigin.Begin); 
     memoryStream.CopyTo(fileStream); 
    } 
} 

事情是它創建並保存壓縮文件到磁盤與預期的文件大小。

但是,當我嘗試在Windows照片查看器中打開它們時,它們似乎已損壞。

任何幫助表示讚賞。

回答

2

幾乎花了3個小時才能找出問題所在。如果你看一下原始圖像的大小並提取一個,則會有一點點差異。

using (var memoryStream = new MemoryStream()) 
{ 
    using (var zip = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) 
    { 
     for (var i = 0; i < images.Length; i++) 
     { 
      var img = images[i]; 
      var file = zip.CreateEntry(i + ".bmp"); 
      using (var stream = new MemoryStream()) 
      { 
       img.Save(stream, ImageFormat.Bmp); 
       using (var entryStream = file.Open()) 
       { 
        var bytes = stream.ToArray(); -- to keep it as image better to have it as bytes 
        entryStream.Write(bytes, 0, bytes.Length); 
       } 
      } 
     } 
    } 

    using (var fileStream = new FileStream(@"test.zip", FileMode.Create)) 
    { 
     memoryStream.Seek(0, SeekOrigin.Begin); 
     memoryStream.CopyTo(fileStream); 
    } 
} 

我已經嘗試過它像魅力一樣工作!

+1

哇,不知道爲什麼把流轉換成bytearray有幫助,但它完全有效。謝啦! –

+0

@john_vanderholt https://stackoverflow.com/questions/46880345/adding-correctly-images-to-ziparchive顯然沒人知道。如果你找到答案,你可以高興或回答 –

相關問題