Gzip压缩和解压

来源:互联网 发布:2048代码 java 编辑:程序博客网 时间:2024/05/17 03:38

转帖地址:
http://www.cnblogs.com/qin0773/archive/2009/06/10/1499864.html里面有详细的一套gzip压缩和解压的代码

http://www.cnblogs.com/dajianshi/archive/2008/03/18/1111180.html

 

压缩代码:

public static byte[] Compress(string s)
{
    byte[] buf = System.Text.Encoding.UTF8.GetBytes(s);
    MemoryStream ms = new MemoryStream();
    byte[] rb;
    GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true);
    gzip.Write(buf, 0, buf.Length);
    gzip.Flush();
    gzip.Close();//必须在ms读出之前关闭掉
    ms.Position = 0;
    rb = new byte[ms.Length];
    ms.Read(rb, 0, (int)ms.Length);
    ms.Close();
    return rb;
}

 

解压代码:

public static string Decompress(byte[] buf)
{
    long totalLength = 0;
    int size = 0;
    MemoryStream ms = new MemoryStream(), msD = new MemoryStream();
    ms.Write(buf, 0, buf.Length);
    ms.Seek(0, SeekOrigin.Begin);
    GZipStream zip;
    zip = new GZipStream(ms, CompressionMode.Decompress);
    byte[] db;
    bool readed = false;
    while (true)
    {
        size = zip.ReadByte();
        if (size != -1)
        {
            if (!readed) readed = true;
            totalLength++;
            msD.WriteByte((byte)size);
        }
        else
        {
            if (readed) break;
        }
    }
    zip.Close();
    db = msD.ToArray();
    msD.Close();
    return System.Text.Encoding.UTF8.GetString(db);
}

 

=======================================================

 

/// 使用GZipStream压缩数据
public static byte[] CompressionData(byte[] input)
{
    byte[] temp = null;
    try
    {
        using (MemoryStream ms = new MemoryStream())
        {
            using (GZipStream compressStream = new GZipStream(ms, CompressionMode.Compress, true))
            {
                // 写入目标流
                compressStream.Write(input, 0, input.Length);
            }
            temp = ms.ToArray();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }

    return temp;
}

/// 解压缩数据
public static byte[] DecompressionData(byte[] input)
{
    byte[] temp = null;
    try
    {
        using (MemoryStream baseData = new MemoryStream())
        {
            MemoryStream rmstemp = new MemoryStream(input);
            using (GZipStream DecompressString = new GZipStream(rmstemp, CompressionMode.Decompress))
            {
                byte[] buff = new byte[4096];
                int n;
                while ((n = DecompressString.Read(buff, 0, buff.Length)) != 0)
                {
                    baseData.Write(buff, 0, n);
                }
            }
            rmstemp.Dispose();
            rmstemp.Close();
            temp = baseData.ToArray();
        }
    }
    catch (Exception ex)
    {
        temp = null;
        throw ex;
    }
    return temp;
}


原创粉丝点击