2017-03-31 90 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