2011-11-21 48 views
0

我想複製在C#中的php函數gzuncompress到目前爲止我得到了以下代碼工作的一部分。請參閱下面的評論和代碼。從字符串錯誤Gzip解壓縮,GZip頭部中的幻數不正確

我在bit []和字符串轉換過程中發生了棘手的問題。 我該如何解決這個問題?我在哪裏錯過了?

我使用的.Net 3.5環境

 var plaintext = Console.ReadLine(); 
     Console.WriteLine("string to byte[] then to string"); 
     byte[] buff = Encoding.UTF8.GetBytes(plaintext); 

     var compress = GZip.GZipCompress(buff); 
     //Uncompress working below 
     try 
     { 
      var unpressFromByte = GZip.GZipUncompress(compress); 
      Console.WriteLine("uncompress successful by uncompress byte[]"); 
     }catch 
     { 
      Console.WriteLine("uncompress failed by uncompress byte[]"); 
     } 

     var compressString = Encoding.UTF8.GetString(compress); 
     Console.WriteLine(compressString); 
     var compressBuff = Encoding.UTF8.GetBytes(compressString); 
     Console.WriteLine(Encoding.UTF8.GetString(compressBuff)); 
     //Uncompress not working below by using string 
     //The magic number in GZip header is not correct 
     try 
     { 
      var uncompressFromString = GZip.GZipUncompress(compressBuff); 
      Console.WriteLine("uncompress successful by uncompress string"); 
     } 
     catch 
     { 
      Console.WriteLine("uncompress failed by uncompress string"); 
     } 

類代碼Gzip已

public static class GZip 
     { 
     public static byte[] GZipUncompress(byte[] data) 
     { 
      using (var input = new MemoryStream(data)) 
      using (var gzip = new GZipStream(input, CompressionMode.Decompress)) 
      using (var output = new MemoryStream()) 
      { 
       gzip.CopyTo(output); 
       return output.ToArray(); 
      } 
     } 
     public static byte[] GZipCompress(byte[] data) 
     { 
      using (var input = new MemoryStream(data)) 
      using (var output = new MemoryStream()) 
      { 
       using (var gzip = new GZipStream(output, CompressionMode.Compress, true)) 
       { 
        input.CopyTo(gzip); 
       } 
       return output.ToArray(); 
      } 
     } 

     public static long CopyTo(this Stream source, Stream destination) 
     { 
      var buffer = new byte[2048]; 
      int bytesRead; 
      long totalBytes = 0; 
      while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) 
      { 
       destination.Write(buffer, 0, bytesRead); 
       totalBytes += bytesRead; 
      } 
      return totalBytes; 
     } 
} 

回答

6

這是不適當的:

var compressString = Encoding.UTF8.GetString(compress); 

compress不是一個UTF-8編碼的一段文字。您應該將其視爲任意二進制數據 - 其中不是適合傳入Encoding.GetString。如果你真的需要任意的二進制數據轉換成文本,使用Convert.ToBase64String(然後用Convert.FromBase64String反向):

var compressString = Convert.ToBase64String(compress); 
Console.WriteLine(compressString); 
var compressBuff = Convert.FromBase64String(compressString); 

,可能會或可能不會匹配PHP做什麼,但它代表任意的二進制的安全方式數據作爲文本,而不像將二進制數據視爲有效的UTF-8編碼文本那樣處理。

+0

非常感謝你,根本沒有想過。它的工作 –

1

我試圖複製在C#中的PHP函數gzuncompress

然後使用GZipStreamDeflateStream內置的類用於此目的的.NET框架。