XMLFileClass.cs 1.5 KB

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