XMLReadWrite.cs 1.8 KB

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