2009-04-12 18 views
4

我很抱歉保守的標題和我的問題本身,但我迷路了。如何在流中使用ICSharpCode.ZipLib?

ICsharpCode.ZipLib提供的示例不包括我正在搜​​索的內容。 我想通過將其放入InflaterInputStream(ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream)來解壓縮一個字節[]

我找到了一個解壓縮函數,但它不起作用。

public static byte[] Decompress(byte[] Bytes) 
    { 
     ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream stream = 
      new ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream(new MemoryStream(Bytes)); 
     MemoryStream memory = new MemoryStream(); 
     byte[] writeData = new byte[4096]; 
     int size; 

     while (true) 
     { 
      size = stream.Read(writeData, 0, writeData.Length); 
      if (size > 0) 
      { 
       memory.Write(writeData, 0, size); 
      } 
      else break; 
     } 
     stream.Close(); 
     return memory.ToArray(); 
    } 

它拋出在線路異常(大小= stream.Read(寫數據,0,writeData.Length);)說它具有無效報頭。

我的問題不是如何修復函數,這個函數沒有提供庫,我只是發現它googling.My的問題是,如何解壓縮與InflaterStream功能相同的方式,但沒有例外。

再次感謝 - 抱歉保守的問題。

回答

1

好吧,它聽起來像數據是不恰當的,否則代碼將工作正常。 (不可否認,我會使用「使用」聲明而不是明確呼叫Close)。

您從哪裏得到您的數據?

1

爲什麼不使用System.IO.Compression.DeflateStream類(自.NET 2.0起可用)?這使用相同的壓縮/解壓縮方法,但不需要額外的庫依賴性。

由於.Net 2.0,如果您需要文件容器支持,您只需要ICSharpCode.ZipLib。

1

lucene中的代碼非常好。

public static byte[] Compress(byte[] input) { 
     // Create the compressor with highest level of compression 
     Deflater compressor = new Deflater(); 
     compressor.SetLevel(Deflater.BEST_COMPRESSION); 

     // Give the compressor the data to compress 
     compressor.SetInput(input); 
     compressor.Finish(); 

     /* 
     * Create an expandable byte array to hold the compressed data. 
     * You cannot use an array that's the same size as the orginal because 
     * there is no guarantee that the compressed data will be smaller than 
     * the uncompressed data. 
     */ 
     MemoryStream bos = new MemoryStream(input.Length); 

     // Compress the data 
     byte[] buf = new byte[1024]; 
     while (!compressor.IsFinished) { 
      int count = compressor.Deflate(buf); 
      bos.Write(buf, 0, count); 
     } 

     // Get the compressed data 
     return bos.ToArray(); 
    } 

    public static byte[] Uncompress(byte[] input) { 
     Inflater decompressor = new Inflater(); 
     decompressor.SetInput(input); 

     // Create an expandable byte array to hold the decompressed data 
     MemoryStream bos = new MemoryStream(input.Length); 

     // Decompress the data 
     byte[] buf = new byte[1024]; 
     while (!decompressor.IsFinished) { 
      int count = decompressor.Inflate(buf); 
      bos.Write(buf, 0, count); 
     } 

     // Get the decompressed data 
     return bos.ToArray(); 
    }