I need to compress a string to reduce the size of a web service response. I see the unit tests in the SharpZipLib samples, but not an example of exactly what I need.
In the following code, the constructor for ZipOutputStream returns the exception: “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);
Where did I get off track? Am I making this more complex than it should be?
Are you sure that the data will be that much smaller after you convert it to Base 64? That will bloat the binary data (zip) significantly. Can’t you solve the issue at the transport level using HTTP compression?
Here’s a post with full source that shows how to do the round-trip zip/unzip.
http://paultechguy.blogspot.com/2008/09/zip-xml-in-memory-for-web-service.html