SerializeClassHelper.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. 
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Runtime.Serialization.Formatters.Binary;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. namespace Common
  11. {
  12. public class SerializeClassHelper
  13. {
  14. ////序列化
  15. //public static void SerialObject(string path,Object obj) {
  16. // FileStream fs = new FileStream(path, FileMode.Create);
  17. // BinaryFormatter bf = new BinaryFormatter();
  18. // bf.Serialize(fs, obj);
  19. // fs.Close();
  20. //}
  21. ////反序列化
  22. //public static Object UnSerialObject(string path) {
  23. // object p = null;
  24. // try
  25. // {
  26. // FileStream fs = new FileStream(path, FileMode.Open);
  27. // BinaryFormatter bf = new BinaryFormatter();
  28. // p = bf.Deserialize(fs);
  29. // fs.Close();
  30. // }
  31. // catch (Exception) { p = null; }
  32. // finally { }
  33. // return p;
  34. //}
  35. public static void SerializeObject( string path, object obj)
  36. {
  37. try
  38. {
  39. string output = Newtonsoft.Json.JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
  40. File.WriteAllText(path, output, Encoding.UTF8);
  41. }
  42. catch(Exception ex) { MessageBox.Show("序列化数据失败:"+ex.Message); }
  43. }
  44. public static object DeserializeObject<T>(string path)
  45. {
  46. try
  47. {
  48. string readText = File.ReadAllText(path, Encoding.UTF8);
  49. return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(readText);
  50. }
  51. catch (Exception ex) { MessageBox.Show("读取序列化数据失败:" + ex.Message); }
  52. return null;
  53. }
  54. }
  55. }