123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
-
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Runtime.Serialization.Formatters.Binary;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace Common
- {
- public class SerializeClassHelper
- {
- ////序列化
- //public static void SerialObject(string path,Object obj) {
- // FileStream fs = new FileStream(path, FileMode.Create);
- // BinaryFormatter bf = new BinaryFormatter();
- // bf.Serialize(fs, obj);
- // fs.Close();
- //}
- ////反序列化
- //public static Object UnSerialObject(string path) {
- // object p = null;
- // try
- // {
- // FileStream fs = new FileStream(path, FileMode.Open);
- // BinaryFormatter bf = new BinaryFormatter();
- // p = bf.Deserialize(fs);
- // fs.Close();
- // }
- // catch (Exception) { p = null; }
- // finally { }
- // return p;
- //}
- public static void SerializeObject( string path, object obj)
- {
- try
- {
- string output = Newtonsoft.Json.JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
- File.WriteAllText(path, output, Encoding.UTF8);
- }
- catch(Exception ex) { MessageBox.Show("序列化数据失败:"+ex.Message); }
- }
- public static object DeserializeObject<T>(string path)
- {
- try
- {
- string readText = File.ReadAllText(path, Encoding.UTF8);
- return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(readText);
- }
- catch (Exception ex) { MessageBox.Show("读取序列化数据失败:" + ex.Message); }
- return null;
- }
- }
- }
|