• 压缩、系列化对象


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.IO.Compression;
    using System.Runtime.Serialization.Formatters.Binary;

    namespace NetMethod
    {
    public class SerializerZip
    {
    public static byte[] Serialize(object obj)
    {
    byte[] buffer = Serializer.Serialize(obj);
    using (MemoryStream stream = new MemoryStream())
    {
    using (GZipStream gzipStream = new GZipStream(stream, CompressionMode.Compress, true))
    {
    gzipStream.Write(buffer, 0, buffer.Length);
    }
    return stream.ToArray();
    }
    }

    public static object DeSerialize(byte[] buffer, int len, int offset = 0)
    {
    object obj = null;
    using (MemoryStream stream = new MemoryStream(buffer, offset,Math.Abs(len)))
    {
    stream.Position = 0;
    using (GZipStream gzipStream = new GZipStream(stream, CompressionMode.Decompress))
    {
    byte[] tempbuffer = new byte[4096];
    int tempoffset = 0;
    using (MemoryStream ms = new MemoryStream())
    {
    while ((tempoffset = gzipStream.Read(tempbuffer, 0, tempbuffer.Length)) != 0)
    {
    ms.Write(tempbuffer, 0, tempoffset);
    }
    ms.Position = 0;
    try
    {
    obj = (object)Serializer.DeSerialize(ms);
    }
    catch
    {

    }
    }
    }
    }
    return obj;
    }
    }

    public static class Serializer
    {
    /// <summary>
    /// 使用二进制序列化对象。
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static byte[] Serialize(object value)
    {
    if (value == null) return null;
    using (MemoryStream stream = new MemoryStream())
    {
    new BinaryFormatter().Serialize(stream, value);
    return stream.ToArray();
    }
    }

    /// <summary>
    /// 使用二进制反序列化对象。
    /// </summary>
    /// <param name="bytes"></param>
    /// <returns></returns>
    public static object DeSerialize(Stream stream)
    {
    return new BinaryFormatter().Deserialize(stream);
    }
    }
    }

  • 相关阅读:
    rabbitmq-高级(死信队列)
    rabbitmq-高级(TTL过期时间)
    springboot整合rabbitmq(topic主题模式)
    springboot整合rabbitmq(direct路由模式)
    glide图片加载库
    自己封装的OKhttp请求
    手机上搭建微型服务器
    listview实现点击条目上的箭头展开隐藏菜单。
    recycleview + checkbox 实现单选
    recycleview中使用checkbox导致的重复选中问题
  • 原文地址:https://www.cnblogs.com/94cool/p/3198439.html
Copyright © 2020-2023  润新知