2009-04-26 142 views
1

這些方法集有什麼問題?.net gzip解壓縮流的問題

 byte[] bytes; 

     using (var memory_stream = new MemoryStream()) 
     using (var gzip_stream = new GZipStream(memory_stream, CompressionMode.Compress)) 
     { 
      var buffer = Encoding.Default.GetBytes("Hello nurse!"); 
      gzip_stream.Write(buffer, 0, buffer.Length); 
      bytes = memory_stream.ToArray(); 
     } 

     int total_read = 0; 

     using (var input_stream = new MemoryStream(bytes)) 
     using (var gzip_stream = new GZipStream(input_stream, CompressionMode.Decompress, true)) 
     { 
      int read; 
      var buffer = new byte[4096]; 
      while ((read = gzip_stream.Read(buffer, 0, buffer.Length)) != 0) { 
       total_read += read; 
      } 
     } 

     Debug.WriteLine(bytes); 
     Debug.WriteLine(total_read); 

gzipStr是一個有效的Gzipped Stream(我可以使用GzipStream()壓縮成功壓縮它)。

爲什麼total_read總是0?是gzip流解壓我的流?難道我做錯了什麼?

我在做什麼錯在這裏??? !!!

回答

2

你忘了沖水。 :)請注意,Encoding.Default通常不應用於生產。在下面,將其替換爲Encoding.UTF8(或其他合適的)。最後,當然,下面的santiy檢查只適用於一切都適用於單個緩衝區。但現在你應該明白了。

kementeus表示我以前的代碼在這裏沒有幫助,所以下面是我使用的確切代碼:

public class GzipBug 
{ 
    public static void Main(String[] a) 
    { 
     byte[] bytes; 
    byte[] buffer; 

    Encoding encoding = Encoding.UTF8; 

     using (var memory_stream = new MemoryStream()) 
     using (var gzip_stream = new GZipStream(memory_stream, CompressionMode.Compress)) 
     { 
      buffer = encoding.GetBytes("Hello nurse!"); 
      gzip_stream.Write(buffer, 0, buffer.Length); 
     gzip_stream.Flush(); 
     bytes = memory_stream.ToArray(); 
     } 

     int total_read = 0; 

     using (var input_stream = new MemoryStream(bytes)) 
     using (var gzip_stream = new GZipStream(input_stream, CompressionMode.Decompress, true)) 
     { 
     int read; 
      buffer = new byte[4096]; 
      while ((read = gzip_stream.Read(buffer, 0, buffer.Length)) != 0) { 
     total_read += read; 
      } 
     } 

     Debug.WriteLine(encoding.GetString(buffer, 0, total_read)); 
     Debug.WriteLine(total_read); 

    } 
} 

它編譯: 的GMC -d:DEBUG -langversion:LINQ -debug + GzipBug。 CS 和運行: MONO_TRACE_LISTENER = Console.Out GzipBug.exe

(你可以刪除MONO_TRACE_LISTENER位)

+0

好吧,我用gzip流你的觀點沖洗並用Encoding.Default/Encoding.UTF8。 B ut我的問題從來沒有涉及gzip壓縮,它工作正常... 我做了你的修改,但總讀_stills_ 0 所以主要問題仍然存在 – kementeus 2009-04-26 19:35:19