Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compress and decompress string in c#

I know there is system.io.compression.gzipstream but it accept a stream as arguments.

I'm looking for a method that accept string

eg.

string compress(string stringtocompress,compressionlevel level);
string decompress(string stringtodecompress);
like image 570
sparrows81 Avatar asked May 17 '13 10:05

sparrows81


2 Answers

you should try this:

using System;
using System.IO;
using System.IO.Compression;
using System.Text;

...

public static string Compress(string s)
{
    var bytes = Encoding.Unicode.GetBytes(s);
    using (var msi = new MemoryStream(bytes))
    using (var mso = new MemoryStream())
    {
        using (var gs = new GZipStream(mso, CompressionMode.Compress))
        {
            msi.CopyTo(gs);
        }
        return Convert.ToBase64String(mso.ToArray());
    }
}

public static string Decompress(string s)
{
    var bytes = Convert.FromBase64String(s);
    using (var msi = new MemoryStream(bytes))
    using (var mso = new MemoryStream())
    {
        using (var gs = new GZipStream(msi, CompressionMode.Decompress))
        {
            gs.CopyTo(mso);
        }
        return Encoding.Unicode.GetString(mso.ToArray());
    }
}
like image 129
Jignesh.Raj Avatar answered Nov 15 '22 07:11

Jignesh.Raj


Please try below, based on this url : http://dreamstatecoding.blogspot.com/2013/04/c-array-compress-and-decompress-with.html. We avoid to use double MemoryStream.

    public static byte[] Compress(string text)
    {
        var bytes = Encoding.Unicode.GetBytes(text);
        using (var mso = new MemoryStream())
        {
            using (var gs = new GZipStream(mso, CompressionMode.Compress))
            {
                gs.Write(bytes, 0, bytes.Length);
            }
            return mso.ToArray();
        }
    }

    public static string Decompress(byte[] data)
    {
        // Read the last 4 bytes to get the length
        byte[] lengthBuffer = new byte[4];
        Array.Copy(data, data.Length - 4, lengthBuffer, 0, 4);
        int uncompressedSize = BitConverter.ToInt32(lengthBuffer, 0);

        var buffer = new byte[uncompressedSize];
        using (var ms = new MemoryStream(data))
        {
            using (var gzip = new GZipStream(ms, CompressionMode.Decompress))
            {
                gzip.Read(buffer, 0, uncompressedSize);
            }
        }
        return Encoding.Unicode.GetString(buffer);            
    }
like image 39
Haryono Avatar answered Nov 15 '22 07:11

Haryono