我需要压缩一个字符串以减小 Web 服务响应的大小。我在 SharpZipLib 示例中看到了单元测试,但并不是我所需要的示例。
在以下代码中,ZipOutputStream 的构造函数返回异常:“No open entry”
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);
我在哪里偏离了轨道?我是否让这比它应该的更复杂?