一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

protobuf对象二进制序列化存储

时间:2022-06-25 07:53:22 编辑:袖梨 来源:一聚教程网

首先下载protobuf库,可以用Nuget。

demo:

 

 代码如下 复制代码

usingSystem;

 

namespaceTools

{

  publicclassBufHelp

  {

    ///

    /// 对象锁

    ///

    privatereadonlystaticObject Locker =newObject();

    /////

    ///// 读写分离锁

    /////

    ///// aaaaa

    //private static ReaderWriterLockSlim rwl = new ReaderWriterLockSlim();

 

    ///

    /// 序列化-表字段业务信息

    ///

    publicstaticboolProtoBufSerialize(T model,stringfilename) where T :class

    {

      try

      {

        stringbinpath = 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(file, model);

            returntrue;

          }

        }

      }

      catch

      {

        returnfalse;

      }

    }

 

    publicstaticT ProtoBufDeserialize(stringfilename) 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(file);

            returnresult;

          }

        }

      }

 

      returndefault(T);

    }

  }

}///

    /// 序列化

    ///

    publicstaticstringSerialize(T t) where T :class

    {

      using(MemoryStream ms =newMemoryStream())

      {

        ProtoBuf.Serializer.Serialize(ms, t);

        returnEncoding.UTF8.GetString(ms.ToArray());

      }

    }

    ///

    /// 反序列化

    ///

    publicstaticT DeSerialize(stringcontent) where T :class

    {

      using(MemoryStream ms =newMemoryStream(Encoding.UTF8.GetBytes(content)))

      {

        T t = ProtoBuf.Serializer.Deserialize(ms);

        returnt;

      }

    }

 

热门栏目