ExtensionMethod.NET Home of 816 C#, Visual Basic, F# and Javascript extension methods

GzipString

if you want to lost wight of string , you can use gzip

Source

public static string CompressString(this string text)
{
    byte[] buffer = Encoding.UTF8.GetBytes(text);
    var memoryStream = new MemoryStream();
    using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
    {
        gZipStream.Write(buffer, 0, buffer.Length);
    }

    memoryStream.Position = 0;

    var compressedData = new byte[memoryStream.Length];
    memoryStream.Read(compressedData, 0, compressedData.Length);

    var gZipBuffer = new byte[compressedData.Length + 4];
    Buffer.BlockCopy(compressedData, 0, gZipBuffer, 4, compressedData.Length);
    Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gZipBuffer, 0, 4);
    return Convert.ToBase64String(gZipBuffer);
}

public static string DecompressString(string compressedText)
{
    byte[] gZipBuffer = Convert.FromBase64String(compressedText);
    using (var memoryStream = new MemoryStream())
    {
        int dataLength = BitConverter.ToInt32(gZipBuffer, 0);
        memoryStream.Write(gZipBuffer, 4, gZipBuffer.Length - 4);

        var buffer = new byte[dataLength];

        memoryStream.Position = 0;
        using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
        {
            gZipStream.Read(buffer, 0, buffer.Length);
        }

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

Example

string zipstring = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".CompressString();

string unzipstring = zipstring.DecompressString();

Author: Phakawan Wongpetanan

Submitted on: 23 jan 2015

Language: C#

Type: Gzip,String

Views: 3191