2012-03-22 136 views
0

我需要壓縮字符串以減小Web服務響應的大小。我在SharpZipLib示例中看到了單元測試,但並不是我需要的示例。SharpZipLib壓縮字符串

在下面的代碼,用於ZipOutputStream構造函數返回異常:「沒有開放准入」

 byte[] buffer = Encoding.UTF8.GetBytes(SomeLargeString); 
     Debug.WriteLine(string.Format("Original byes of string: {0}", buffer.Length)); 

     MemoryStream ms = new MemoryStream(); 
     using (ZipOutputStream zipStream = new ZipOutputStream(ms)) 
     { 
      zipStream.Write(buffer, 0, buffer.Length); 
      Debug.WriteLine(string.Format("Compressed byes: {0}", ms.Length)); 
     } 

     ms.Position = 0; 
     MemoryStream outStream = new MemoryStream(); 

     byte[] compressed = new byte[ms.Length]; 
     ms.Read(compressed, 0, compressed.Length); 

     byte[] gzBuffer = new byte[compressed.Length + 4]; 
     System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length); 
     System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4); 
     string compressedString = Convert.ToBase64String (gzBuffer); 

哪裏我下車的軌道?我是否讓這件事比應該更復雜?

回答

2

與您的代碼的幾個問題:

  1. 要衝洗數據時,你流的工作。

  2. 要從一個MemoryStream讀出的數據,只需使用:

    字節[]數據= ms.ToArray();

  3. Zip文件是可能包含多個條目(文件),註釋的容器...您可能需要調用PutNextEntry()以在開始向其寫入數據之前添加新條目。

  4. 如果你只需要壓縮單個數據流(這是你的情況),你最好的選擇是簡單地使用壓縮單個數據流的壓縮(或壓縮)壓縮(實際上是zip格式內部使用gzip壓縮其條目...) .Net提供了2個非常方便的數據壓縮類:GZipStream和DeflateStream。一個很好的樣本,可以發現here

3

Web服務通信壓縮數據從Silverlight的我用這個片段:

private byte[] zipText(string text) 
{ 
    if (text == null) 
     return null; 

    using(Stream memOutput = new MemoryStream()) 
    { 
     using (GZipOutputStream zipOut = new GZipOutputStream(memOutput)) 
     { 
      using (StreamWriter writer = new StreamWriter(zipOut)) 
      { 
       writer.Write(text); 

       writer.Flush(); 
       zipOut.Finish(); 

       byte[] bytes = new byte[memOutput.Length]; 
       memOutput.Seek(0, SeekOrigin.Begin); 
       memOutput.Read(bytes, 0, bytes.Length); 

       return bytes; 
      } 
     } 
    } 
} 

private string unzipText(byte[] bytes) 
{ 
    if (bytes == null) 
     return null; 

    using(Stream memInput = new MemoryStream(bytes)) 
    using(GZipInputStream zipInput = new GZipInputStream(memInput)) 
    using(StreamReader reader = new StreamReader(zipInput)) 
    { 
     string text = reader.ReadToEnd(); 

     return text; 
    } 
} 
  1. 我用來代替Zip壓縮
  2. 預計到文本的GZip可以從類似的環境讀/寫,所以我沒有做任何額外的編碼/解碼。

我的情況是json數據的壓縮。根據我的觀察,在某些情況下,大約95Kb的文本數據被壓縮到1.5Kb。所以即使數據將被序列化到64位,無論如何都是很好的流量節省。

發表我的答案,可能會有人省些時間。