protobuf Object Binary Serialization Storage of Detailed Explanation

  • 2021-12-09 09:43:02
  • OfStack

First download the protobuf library, which can be used with Nuget.

demo:


using System;

namespace Tools
{
  public class BufHelp
  {
    /// <summary>
    ///  Object lock 
    /// </summary>
    private readonly static Object Locker = new Object();
    ///// <summary>
    /////  Read-write separation lock 
    ///// </summary>
    ///// <remarks>aaaaa</remarks>
    //private static ReaderWriterLockSlim rwl = new ReaderWriterLockSlim();

    /// <summary>
    ///  Serialization - Table field business information 
    /// </summary>
    public static bool ProtoBufSerialize<T>(T model, string filename) where T : class
    {
      try
      {
        string binpath = Config.KeyCenter.KeyBaseDirectory + @"Config\";

        if (!System.IO.Directory.Exists(binpath))
          System.IO.Directory.CreateDirectory(binpath);

        lock (Locker)
        {
          using (var file = System.IO.File.Create(binpath + filename))
          {
            ProtoBuf.Serializer.Serialize<T>(file, model);
            return true;
          }
        }
      }
      catch
      {
        return false;
      }
    }

    public static T ProtoBufDeserialize<T>(string filename) where T : class
    {
      var dbpath = Config.KeyCenter.KeyBaseDirectory + @"Config\" + filename;

      if (System.IO.File.Exists(dbpath))
      {
        lock (Locker)
        {
          using (var file = System.IO.File.OpenRead(dbpath))
          {
            var result = ProtoBuf.Serializer.Deserialize<T>(file);
            return result;
          }
        }
      }

      return default(T);
    }
  }
}/// <summary>
    ///  Serialization 
    /// </summary>
    public static string Serialize<T>(T t) where T : class
    {
      using (MemoryStream ms = new MemoryStream())
      {
        ProtoBuf.Serializer.Serialize<T>(ms, t);
        return Encoding.UTF8.GetString(ms.ToArray());
      }
    }
    /// <summary>
    ///  Deserialization 
    /// </summary>
    public static T DeSerialize<T>(string content) where T : class
    {
      using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(content)))
      {
        T t = ProtoBuf.Serializer.Deserialize<T>(ms);
        return t;
      }
    }


Related articles: