XMLReadWrite.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //XML读写类
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Xml.Serialization;
  9. namespace MvvmScaffoldFrame48.DLL.ConfigTools
  10. {
  11. public static class XMLReadWrite
  12. {
  13. /// <summary>
  14. /// 序列化对象到XML文件
  15. /// </summary>
  16. /// <typeparam name="T"></typeparam>
  17. /// <param name="data"></param>
  18. /// <param name="filePath"></param>
  19. /// <exception cref="InvalidOperationException"></exception>
  20. public static void SerializeToXml<T>(T data, string filePath)
  21. {
  22. try
  23. {
  24. var serializer = new XmlSerializer(typeof(T));
  25. using (var writer = new StreamWriter(filePath))
  26. {
  27. serializer.Serialize(writer, data);
  28. }
  29. }
  30. catch (Exception ex)
  31. {
  32. throw new InvalidOperationException("XML serialization failed", ex);
  33. }
  34. }
  35. /// <summary>
  36. /// 从XML文件反序列化对象
  37. /// </summary>
  38. /// <typeparam name="T"></typeparam>
  39. /// <param name="filePath"></param>
  40. /// <returns></returns>
  41. /// <exception cref="InvalidOperationException"></exception>
  42. public static T DeserializeFromXml<T>(string filePath)
  43. {
  44. try
  45. {
  46. var serializer = new XmlSerializer(typeof(T));
  47. using (var reader = new StreamReader(filePath))
  48. {
  49. return (T)serializer.Deserialize(reader);
  50. }
  51. }
  52. catch (Exception ex)
  53. {
  54. throw new InvalidOperationException("XML deserialization failed", ex);
  55. }
  56. }
  57. }
  58. }