C#数据序列化与反序列化以及压缩与解压缩

本文档详细介绍了如何使用BinaryFormatter进行序列化和反序列化操作,以及如何利用GZipStream实现数据的压缩与解压。重点展示了MemoryStream和BinaryFormatter在.NET中的应用,适合理解和实践基础的数据处理技术。
摘要由CSDN通过智能技术生成

序列化:

        public static byte[] Serialize<T>(T msg)
        {
            using (MemoryStream ms=new MemoryStream())
            {
                try
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    bf.Serialize(ms, msg);
                    ms.Seek(0, SeekOrigin.Begin);
                    return ms.ToArray();
                }
                catch (SerializationException e)
                {
                    throw;
                }
            }
        }

反序列化:

        public static T DeSerialize<T>(byte[] bytes)
        {
            using (MemoryStream ms = new MemoryStream(bytes))
            {
                try
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    T msg = (T)bf.Deserialize(ms);
                    return msg;
                }
                catch (SerializationException e)
                {
                    throw;
                }
            }
        }

压缩:

        public static byte[] Compress(byte[] input) {
            using(MemoryStream outMS = new MemoryStream()) {
                using(GZipStream gzs = new GZipStream(outMS, CompressionMode.Compress, true)) {
                    gzs.Write(input, 0, input.Length);
                    gzs.Close();
                    return outMS.ToArray();
                }
            }
        }

解压:

        public static byte[] DeCompress(byte[] input) {
            using(MemoryStream inputMS = new MemoryStream(input)) {
                using(MemoryStream outMs = new MemoryStream()) {
                    using(GZipStream gzs = new GZipStream(inputMS, CompressionMode.Decompress)) {
                        byte[] bytes = new byte[1024];
                        int len = 0;
                        while((len = gzs.Read(bytes, 0, bytes.Length)) > 0) {
                            outMs.Write(bytes, 0, len);
                        }
                        gzs.Close();
                        return outMs.ToArray();
                    }
                }
            }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值