在c#中压缩和解压缩字符串

时间:2013-05-17 10:12:30

标签: asp.net zip compression

我知道有system.io.compression.gzipstream但它接受一个流作为参数。

我正在寻找一种接受字符串

的方法

例如

string compress(string stringtocompress,compressionlevel level);
string decompress(string stringtodecompress);

2 个答案:

答案 0 :(得分:15)

你应该试试这个:

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());
    }
}

答案 1 :(得分:1)

请根据以下URL尝试以下操作:http://dreamstatecoding.blogspot.com/2013/04/c-array-compress-and-decompress-with.html我们避免使用双重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);            
    }