Thursday, 10 October 2013

How To Compress and Decompress Strings in C Sharp

You need the way to compress the information you write to a file victimization one amongst the stream-based categories. additionally, you would like the way to decompress the information from this compressed file once you scan it back in.

Use the System.IO.Compression.DeflateStream or the System.IO.Compression. GZipStream categories to scan and write compressed knowledge to a file. The Compress and DeCompress ways shown below demonstrate a way to use these categories to compress and expand knowledge on the fly.


EXAMPLE:
using System.IO.Compression;
using System.Text;
using System.IO;

public class Demo
{
    publicstaticstring 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 = newbyte[ms.Length];
        ms.Read(compressed, 0, compressed.Length);

        byte[] gzBuffer = newbyte[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);
    }

    publicstaticstring 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 = newbyte[msgLength];

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

            return Encoding.UTF8.GetString(buffer);
        }
    }
}

Remember that strings need to be longer than 3 to 400 characters; otherwise the compression rate is not good enough. I hope you will like this article.

0 comments:

Post a Comment