I'm trying to compress an string in one module and decompressing it in another module. Here is the code I'm using.
Compress
public static string CompressString(string text)
{
byte[] buffer = Encoding.ASCII.GetBytes(text);
MemoryStream ms = new MemoryStream();
using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
{
zip.Write(buffer, 0, buffer.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);
return Convert.ToBase64String(gzBuffer);
}
Decompress
public static byte[] DecompressString(byte[] data)
{
using (var compressedStream = new MemoryStream(data))
using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
using (var resultStream = new MemoryStream())
{
zipStream.CopyTo(resultStream);
return resultStream.ToArray();
}
}
Using it as:
DecompressString(System.Text.Encoding.ASCII.GetBytes(ip));
But, for above statement, I'm getting following error.
{"The magic number in GZip header is not correct. Make sure you are passing in a GZip stream."} System.SystemException {System.IO.InvalidDataException}
DecompressString(Convert.FromBase64String(ip));
would make more sense. (Although I'd also suggest that your methods should be symmetric, e.g. make them both accept and return strings, or maybebyte[] Compress(string)
andstring Decompress(byte[])
. – Gard