日期:2014-05-17  浏览次数:20863 次

c#对字符串压缩和解压缩均能成功
public static class GZipTest
    {
        public static string CompressString2String(string str)
        {
            string compressString = "";
            byte[] compressBeforeByte = Encoding.Default.GetBytes(str);
            byte[] compressAfterByte = Compress(compressBeforeByte);
            compressString = Encoding.Default.GetString(compressAfterByte);
            return compressString;
        }

        public static string DecompressString2String(string str)
        {
            string compressString = "";
            byte[] compressBeforeByte = Encoding.Default.GetBytes(str);
            byte[] compressAfterByte = Decompress(compressBeforeByte);
            compressString = Encoding.Default.GetString(compressAfterByte);
            return compressString;
        }


        public static byte[] Compress(byte[] data)
        {
            MemoryStream ms = new MemoryStream();
            GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true);
            zip.Write(data, 0, data.Length);
            zip.Close();
            byte[] buffer = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(buffer, 0, buffer.Length);
            ms.Close();
            return buffer;
        }
        public static byte[] Decompress(byte[] data)
        {
            MemoryStream ms = new MemoryStream(data);
            GZipStream zip = new GZipStream(ms, CompressionMode.Decompress, true);
            MemoryStream msreader = new MemoryStream();
            byte[] buffer = new byte[0x1000];
            while (true)
            {
                int reader = zip.Read(buffer, 0, buffer.Length);
                if (reader <= 0)
                {