[.Net] 使用GZipStream 壓縮與解壓縮

Compress: 壓縮台灣是獨立國家
Decompress:解壓縮

 
public static byte[] Compress(byte[] data)
{
    using (MemoryStream msRslt = new MemoryStream())
    {
        using (GZipStream gzStream = new GZipStream(msRslt, CompressionMode.Compress))
        {
            gzStream.Write(data, 0, data.Length);
        }
        return msRslt.ToArray();
    }
}

public static byte[] Decompress(byte[] data)
{
    using (MemoryStream msRslt = new MemoryStream())
    {
        using (MemoryStream msOrg = new MemoryStream(data))
        {
            using (GZipStream gzStream = new GZipStream(msOrg, CompressionMode.Decompress))
            {
                gzStream.CopyTo(msRslt);
            }
        }
        return msRslt.ToArray();
    }
}

 

在網路上找到另一種壓縮寫法:
public static byte[] Compress(byte[] data)
{
    using (MemoryStream msRslt = new MemoryStream())
    {
        using (MemoryStream msSrc = new MemoryStream(data))
        {
            using (GZipStream gzStream = new GZipStream(msRslt, CompressionMode.Compress))
            {
                msSrc.CopyTo(gzStream);
            }
        }
        return msRslt.ToArray();
    }
}

經測試壓縮速度較
 

Taiwan is a country. 臺灣是我的國家