Question Compressed String Length is high


New member
Aug 13, 2013
Programming Experience

i have a string and i encrypt it and than Compressed that string.

Result is Length of the Compressed string is high.

I'm using the below code snippet

public static string Compress(string text)        {
            byte[] buffer = Encoding.UTF8.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);

        public static string Decompress(string compressedText)
            byte[] gzBuffer = Convert.FromBase64String(compressedText);
            using (MemoryStream ms = new MemoryStream())
                int msgLength = BitConverter.ToInt32(gzBuffer, 0);
                ms.Write(gzBuffer, 4, gzBuffer.Length-4);

                byte[] buffer = new byte[msgLength];

                ms.Position = 0;

                using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))
                    zip.Read(buffer, 0, buffer.Length);

                return Encoding.UTF8.GetString(buffer);

Please help me to resolve this problem
There is overhead with zip compression, if you for example compress a single Char you will get 125 bytes. You will start to see compression take effect with input strings of a few hundred chars.

Base64 encoding will also expand the length of input bytes with about 3 to 4 ratio.
Top Bottom