数据压缩与解压缩

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/JeanShaw/article/details/81938980

数据压缩与解压缩需要用到一个已经编译好的dll,名字叫 ICSharpCode.SharpZipLib,可以直接到我上传的资源中下载,1积分,地址:DLL下载,源码来自商业游戏源码。

     /**
     * 压缩的方式 
     * @param str
     * @return
     * @throws IOException
     */
    public static string compressByGZIP(string str)
    {
        if (string.IsNullOrEmpty(str)) 
        {
            return str;
        }
        MemoryStream ms = new MemoryStream();
        GZipOutputStream gzip = new GZipOutputStream(ms);
        byte[] binary = Encoding.UTF8.GetBytes(str);
        gzip.Write(binary, 0, binary.Length);
        gzip.Finish();
        gzip.Flush();
        gzip.Close();
        byte[] press = ms.ToArray();
        return Encoding.GetEncoding("ISO-8859-1").GetString(press);
    }

对应的解压的代码:

     /**
     * 解压缩
     * @param str
     * @return
     * @throws IOException
     */
    public static string uncompressByGZIP(string str)
    {
        if (string.IsNullOrEmpty(str)) 
        {
            return null;
        }
        byte[] press=Encoding.GetEncoding("ISO-8859-1").GetBytes(str);
        GZipInputStream gzi = new GZipInputStream(new MemoryStream(press));
        MemoryStream re = new MemoryStream();
        int count=0;
        byte[] data=new byte[256];
        while ((count = gzi.Read(data, 0, data.Length)) != 0)
        {
            re.Write(data,0,count);
        }
        byte[] depress = re.ToArray();
        return Encoding.UTF8.GetString(depress);
    }

将数据压缩后,使用前请先解压,使用此方法可以进行包的优化,也有利用数据安全。

猜你喜欢

转载自blog.csdn.net/JeanShaw/article/details/81938980