SoFunction
Updated on 2025-03-07

Protobuf object binary serialization storage (detailed explanation)

First download the protobuf library, you can use Nuget.

demo:

using System;

namespace Tools
{
  public class BufHelp
  {
    /// <summary>
    /// Object lock    /// </summary>
    private readonly static Object Locker = new Object();
    ///// <summary>
    ////// Read and 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\";

        if (!(binpath))
          (binpath);

        lock (Locker)
        {
          using (var file = (binpath + filename))
          {
            <T>(file, model);
            return true;
          }
        }
      }
      catch
      {
        return false;
      }
    }

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

      if ((dbpath))
      {
        lock (Locker)
        {
          using (var file = (dbpath))
          {
            var result = <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())
      {
        <T>(ms, t);
        return Encoding.(());
      }
    }
    /// <summary>
    /// Deserialization    /// </summary>
    public static T DeSerialize<T>(string content) where T : class
    {
      using (MemoryStream ms = new MemoryStream(Encoding.(content)))
      {
        T t = <T>(ms);
        return t;
      }
    }

The above article on the binary serialized storage of protobuf objects (detailed explanation) is all the content I share with you. I hope you can give you a reference and I hope you can support me more.