2017-03-31 89 views
1

我有我要壓縮內存流:SharpZipLib不壓縮內存流

public static MemoryStream ZipChunk(MemoryStream unZippedChunk) { 

     MemoryStream zippedChunk = new MemoryStream(); 

     ZipOutputStream zipOutputStream = new ZipOutputStream(zippedChunk); 
     zipOutputStream.SetLevel(3); 

     ZipEntry entry = new ZipEntry("name"); 
     zipOutputStream.PutNextEntry(entry); 

     Utils.StreamCopy(unZippedChunk, zippedChunk, new byte[4096]); 
     zipOutputStream.CloseEntry(); 

     zipOutputStream.IsStreamOwner = false; 
     zipOutputStream.Close(); 
     zippedChunk.Close(); 

     return zippedChunk; 
    } 

public static void StreamCopy(Stream source, Stream destination, byte[] buffer, bool bFlush = true) { 
     bool flag = true; 
     while (flag) { 

      int num = source.Read(buffer, 0, buffer.Length); 
      if (num > 0) {      
       destination.Write(buffer, 0, num); 
      } 

      else { 

       if (bFlush) {       
        destination.Flush(); 
       } 

       flag = false; 
      } 
     }   
    } 

這應該是相當簡單的。你提供一個你想壓縮的流。這些方法壓縮流並返回它。大。

但是,我沒有得到壓縮流。我得到的是在開始和結束處添加大約20個字節的流,這似乎與zip庫有關。但中間的數據是完全未壓縮的(256個字節的數值範圍相同,等等)。我嘗試將等級提高到9,但沒有任何變化。

爲什麼我的流不能壓縮?

回答

1

你自己複製原始數據流直接進入輸出流通過:

Utils.StreamCopy(unZippedChunk, zippedChunk, new byte[4096]); 

您應該複製到zipOutputStream代替:

StreamCopy(unZippedChunk, zipOutputStream, new byte[4096]); 

邊注:代替使用自定義副本流的方法 - 使用默認一個:

unZippedChunk.CopyTo(zipOutputStream); 
+0

我知道我錯過了一些愚蠢的東西,我只是看不到它。謝謝! – Karlovsky120

+0

請注意,沒有恢復位置返回內存流是... –

+0

明白了。將解決它。 – Karlovsky120