使用2.0中的压缩流减少网络传输量

  public static byte[] Compress(DataSet ds)
        {
            BinaryFormatter ser = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            //Binary 作为二进制内容序列化。仅可在 ADO.NET 2.0 中使用
            ds.RemotingFormat = SerializationFormat.Binary;
            //序列化到MemoryStream
            ser.Serialize(ms, ds);
            //压缩后的MemoryStream
            MemoryStream compressMs = new MemoryStream();
            // 写入压缩的MemoryStream
            GZipStream compressedStream = new GZipStream(compressMs, CompressionMode.Compress, true);
            compressedStream.Write(ms.ToArray(), 0, ms.ToArray().Length);
            return compressMs.ToArray();

        }


        public static DataSet Decompress(byte[] data)
        {
            MemoryStream unCompressMS = new MemoryStream();
            MemoryStream compressMS = new MemoryStream(data);
            GZipStream decompressedStream = new GZipStream(unCompressMS, CompressionMode.Decompress, true);
            decompressedStream.Write(compressMS.ToArray(), 0, compressMS.ToArray().Length);
            BinaryFormatter ser = new BinaryFormatter();
            return (DataSet)ser.Deserialize(unCompressMS);
        } 

 

比较了一下,使用压缩与不使用压缩的有明显的优势,差不多是在十分之一的流量左右

posted @ 2006-12-03 22:44  greystar  阅读(127)  评论(0编辑  收藏  举报