XmlHelper.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.IO;
  3. using System.Xml.Serialization;
  4. namespace WWPipeLine.Commons.SerializeHelper
  5. {
  6. /// <summary>
  7. /// Xml 序列化和反序列化类
  8. /// </summary>
  9. public class XmlHelper
  10. {
  11. /// <summary>
  12. /// 序列化对象为XML文件
  13. /// </summary>
  14. /// <typeparam name="T">序列化对象</typeparam>
  15. /// <param name="fileName">序列化文件路径</param>
  16. /// <param name="t">序列化对象</param>
  17. /// <returns></returns>
  18. public static bool SerializedToXml<T>(string fileName, T t)
  19. {
  20. try
  21. {
  22. Type paramType = t.GetType();
  23. XmlSerializer xmls = new XmlSerializer(paramType);
  24. using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
  25. {
  26. xmls.Serialize(fs, t);
  27. }
  28. return true;
  29. }
  30. catch (Exception ex)
  31. {
  32. System.Diagnostics.Debug.WriteLine("Serialize xml Error:" + ex.ToString());
  33. return false;
  34. }
  35. }
  36. /// <summary>
  37. /// 反序列化对象
  38. /// </summary>
  39. /// <typeparam name="T">反序列化的对象</typeparam>
  40. /// <param name="fileName">反序列化文件的路径</param>
  41. /// <param name="t">反序列化出来的路径</param>
  42. /// <returns></returns>
  43. public static bool DeSerializedFromXml<T>(string fileName, ref T t)
  44. {
  45. try
  46. {
  47. Type paramType = t.GetType();
  48. XmlSerializer xmls = new XmlSerializer(paramType);
  49. using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
  50. {
  51. t = (T)xmls.Deserialize(fs);
  52. }
  53. return true;
  54. }
  55. catch (Exception ex)
  56. {
  57. System.Diagnostics.Debug.WriteLine("DeSerialize xml Error:" + ex.ToString());
  58. return false;
  59. }
  60. }
  61. }
  62. }