2011-06-14 169 views
4

我建(基於一個CodeProject上的文章)包裝類(C#)來的MemoryStream使用GZipStream來壓縮MemoryStream。它壓縮好,但不解壓縮。我看過很多其他有相同問題的例子,我覺得我遵循所說的內容,但是當我解壓縮時仍然沒有獲得任何東西。這裏的壓縮和解壓方法:編程壓縮/解壓縮與GZipStream

public static byte[] Compress(byte[] bSource) 
{ 

    using (MemoryStream ms = new MemoryStream()) 
    { 
     using (GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true)) 
     { 
      gzip.Write(bSource, 0, bSource.Length); 
      gzip.Close(); 
     } 

     return ms.ToArray(); 
    } 
} 


public static byte[] Decompress(byte[] bSource) 
{ 

    try 
    { 
     using (MemoryStream ms = new MemoryStream()) 
     { 
      using (GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress, true)) 
      { 
       gzip.Read(bSource, 0, bSource.Length); 
       gzip.Close(); 
      } 

      return ms.ToArray(); 
     } 
    } 
    catch (Exception ex) 
    { 
     throw new Exception("Error decompressing byte array", ex); 
    } 
} 

這裏是我如何使用它的一個例子:

string sCompressed = Convert.ToBase64String(CompressionHelper.Compress("Some Text")); 
// Other Processes 
byte[] bReturned = CompressionHelper.Decompress(Convert.FromBase64String(sCompressed)); 
// bReturned has no elements after this line is executed 

回答

7

有一個在解壓縮方法的錯誤。

該代碼未讀取bSource的內容。相反,它覆蓋了它的內容,只能從空的內存流中創建的空的gzip讀取。

基本上就是你的代碼版本是這樣做的:

//create empty memory 
using (MemoryStream ms = new MemoryStream()) 

//create gzip stream over empty memory stream 
using (GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true)) 

// write from empty stream to bSource 
gzip.Write(bSource, 0, bSource.Length); 

的修復看起來是這樣的:

public static byte[] Decompress(byte[] bSource) 
{ 
    using (var inStream = new MemoryStream(bSource)) 
    using (var gzip = new GZipStream(inStream, CompressionMode.Decompress)) 
    using (var outStream = new MemoryStream()) 
    { 
     gzip.CopyTo(outStream); 
     return outStream.ToArray(); 
    } 
} 
1

的OP在編輯說,現在回滾:

感謝Alex對錯誤的解釋,我能夠解決Decompress方法。不幸的是,我使用.Net 3.5,所以我無法實現他建議的Stream.CopyTo方法。不過,他的解釋讓我能夠找出解決方案。我對下面的Decompress方法做了適當的修改。

public static byte[] Decompress(byte[] bSource) 
    { 
     try 
     { 
      using (var instream = new MemoryStream(bSource)) 
      { 
       using (var gzip = new GZipStream(instream, CompressionMode.Decompress)) 
       { 
        using (var outstream = new MemoryStream()) 
        { 
         byte[] buffer = new byte[4096]; 

         while (true) 
         { 
          int delta = gzip.Read(buffer, 0, buffer.Length); 

          if (delta > 0) 
           outstream.Write(buffer, 0, delta); 

          if (delta < 4096) 
           break; 
         } 
         return outstream.ToArray(); 
        } 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      throw new Exception("Error decompressing byte array", ex); 
     } 
    }