文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>使用gzip压缩字符串

使用gzip压缩字符串

时间:2011-01-13  来源:冯小诺

    static string CompressString(string input)
        {
            string retValue = string.Empty;
            if (!string.IsNullOrEmpty(input))
            {
                byte[] byteSource = Encoding.UTF8.GetBytes(input);
                MemoryStream msm = new MemoryStream();
                using (GZipStream gzs = new GZipStream(msm, CompressionMode.Compress, true))
                {
                    gzs.Write(byteSource, 0, byteSource.Length);
                }

                msm.Position = 0;

                byte[] compBytes = new byte[msm.Length];
                msm.Read(compBytes, 0, compBytes.Length);

                msm.Close();

                byte[] finalBuffer = new byte[compBytes.Length + 4];
                Buffer.BlockCopy(compBytes, 0, finalBuffer, 4, compBytes.Length);
                Buffer.BlockCopy(BitConverter.GetBytes(byteSource.Length), 0, finalBuffer, 0, 4);

                retValue = System.Convert.ToBase64String(finalBuffer);
            }

            return retValue;
        }

        static string DecompressString(string input)
        {
            string retValue = string.Empty;
            if (!string.IsNullOrEmpty(input))
            {
                byte[] source = System.Convert.FromBase64String(input);
                using (MemoryStream msm = new MemoryStream())
                {
                    int length = BitConverter.ToInt32(source, 0);
                    msm.Write(source, 4, source.Length - 4);

                    //Console.WriteLine(Encoding.UTF8.GetString(source));

                    msm.Position = 0;
                    byte[] decmpBytes = new byte[length];
                    using (GZipStream gzs = new GZipStream(msm, CompressionMode.Decompress))
                    {
                        gzs.Read(decmpBytes, 0, length);

                        //gzs.CopyTo();
                    }

                    retValue = Encoding.UTF8.GetString(decmpBytes);
                }
            }

            return retValue;
        }
相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载