利用GZipStream加压与解压字符串

最近要用webservice传递字符串,由于数据量不是很大,所以选择微软提供的GZipStream加压与解压。

这里是加压其实很简单,就是将传入的byte数组直接用GZipStream写到一个新的内存流里面去

  
public static byte [] Compress( byte [] bytes)
{
using (MemoryStream ms = new MemoryStream())
{
GZipStream Compress
= new GZipStream(ms, CompressionMode.Compress);

Compress.Write(bytes,
0 , bytes.Length);

Compress.Close();

return ms.ToArray();

}
}

因为我是用的.ne Framwork 4.0 所以GZipStream有CopyTo这个方法,但是4.0以下就没有这个方法。如果4.0以下只有在用一个BinaryReader

在去读取

  
public static byte [] Decompress(Byte[] bytes)
{
using (MemoryStream tempMs = new MemoryStream())
{
using (MemoryStream ms = new MemoryStream(bytes))
{
GZipStream Decompress
= new GZipStream(ms, CompressionMode.Decompress);

Decompress.CopyTo(tempMs);

Decompress.Close();

return tempMs.ToArray();
}
}
}
附上全部代码
 
using System;
using System.Text;
using System.IO;
using System.IO.Compression;
using System.Collections.Generic;

namespace DatabaseUtilLib
{

    public class ZipWrapper
    {

        public static string Compress(string str)
        {
            //因输入的字符串不是Base64所以转换为Base64,因为HTTP如果不传递Base64则会发生http 400错误
            return Convert.ToBase64String(Compress(Convert.FromBase64String(Convert.ToBase64String(Encoding.Default.GetBytes(str)))));
        }

        public static string Decompress(string str)
        {
            return Encoding.Default.GetString(Decompress(Convert.FromBase64String(str)));
        }

        public static byte[] Compress(byte[] bytes)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                GZipStream Compress = new GZipStream(ms, CompressionMode.Compress);

                Compress.Write(bytes, 0, bytes.Length);

                Compress.Close();

                return ms.ToArray();

            }
        }

        public static byte[] Decompress(Byte[] bytes)
        {
            using (MemoryStream tempMs = new MemoryStream())
            {
                using (MemoryStream ms = new MemoryStream(bytes))
                {
                    GZipStream Decompress = new GZipStream(ms, CompressionMode.Decompress);

                    Decompress.CopyTo(tempMs);

                    Decompress.Close();

                    return tempMs.ToArray();
                }
            }
        }
    }
}

你可能感兴趣的:(Stream)