The code to compress/decompress a string
public static void CopyTo(Stream src, Stream dest) {
byte[] bytes = new byte[4096];
int cnt;
while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0) {
dest.Write(bytes, 0, cnt);
}
}
public static byte[] Zip(string str) {
var bytes = Encoding.UTF8.GetBytes(str);
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream()) {
using (var gs = new GZipStream(mso, CompressionMode.Compress)) {
//msi.CopyTo(gs);
CopyTo(msi, gs);
}
return mso.ToArray();
}
}
public static string Unzip(byte[] bytes) {
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream()) {
using (var gs = new GZipStream(msi, CompressionMode.Decompress)) {
//gs.CopyTo(mso);
CopyTo(gs, mso);
}
return Encoding.UTF8.GetString(mso.ToArray());
}
}
static void Main(string[] args) {
byte[] r1 = Zip("StringStringStringStringStringStringStringStringStringStringStringStringStringString");
string r2 = Unzip(r1);
}
Remember that Zip
returns a byte[]
, while Unzip
returns a string
. If you want a string from Zip
you can Base64 encode it (for example by using Convert.ToBase64String(r1)
) (the result of Zip
is VERY binary! It isn't something you can print to the screen or write directly in an XML)
The version suggested is for .NET 2.0, for .NET 4.0 use the MemoryStream.CopyTo
.
IMPORTANT: The compressed contents cannot be written to the output stream until the GZipStream
knows that it has all of the input (i.e., to effectively compress it needs all of the data). You need to make sure that you Dispose()
of the GZipStream
before inspecting the output stream (e.g., mso.ToArray()
). This is done with the using() { }
block above. Note that the GZipStream
is the innermost block and the contents are accessed outside of it. The same goes for decompressing: Dispose()
of the GZipStream
before attempting to access the data.