zoukankan      html  css  js  c++  java
  • 压缩、系列化对象

    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);
    }
    }
    }

  • 相关阅读:
    C#变量
    C#数据类型、标识符和关键字
    【算法】Hough变换
    RANSAC 剔除错误匹配 估计模型
    【Hector slam】A Flexible and Scalable SLAM System with Full 3D Motion Estimation
    【排序】插入排序:最稳定:时间复杂度O(n^2)
    【matlab】查看程序运行时间
    【matlab】合并两个cell
    【matlab】膨胀
    【ros】.bag文件
  • 原文地址:https://www.cnblogs.com/94cool/p/3198439.html
Copyright © 2011-2022 走看看