首先下载protobuf库,可以用Nuget。
demo:
代码如下 | 复制代码 |
usingSystem;
namespaceTools { publicclassBufHelp { /// /// 对象锁 /// privatereadonlystaticObject Locker =newObject(); ///// ///// 读写分离锁 ///// ///// //private static ReaderWriterLockSlim rwl = new ReaderWriterLockSlim();
/// /// 序列化-表字段业务信息 /// publicstaticboolProtoBufSerialize { 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 returntrue; } } } catch { returnfalse; } }
publicstaticT ProtoBufDeserialize { 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 returnresult; } } }
returndefault(T); } } }/// /// 序列化 /// publicstaticstringSerialize { using(MemoryStream ms =newMemoryStream()) { ProtoBuf.Serializer.Serialize returnEncoding.UTF8.GetString(ms.ToArray()); } } /// /// 反序列化 /// publicstaticT DeSerialize { using(MemoryStream ms =newMemoryStream(Encoding.UTF8.GetBytes(content))) { T t = ProtoBuf.Serializer.Deserialize returnt; } } |