XmlSerializer.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. using System.Xml;
  9. using System.Xml.Linq;
  10. namespace MECF.Framework.Common.Config
  11. {
  12. public static class XmlSerializerExtension
  13. {
  14. public static T Read<T>(string fileName, out string reason) where T : class
  15. {
  16. try
  17. {
  18. reason = string.Empty;
  19. if (!File.Exists(fileName))
  20. {
  21. reason = $"{fileName}文件名不存在";
  22. return null;
  23. }
  24. using (StreamReader fs = new StreamReader(fileName))
  25. {
  26. XmlSerializer serializer = new XmlSerializer(typeof(T));
  27. return (serializer.Deserialize(fs) as T);
  28. }
  29. }
  30. catch (Exception ex)
  31. {
  32. reason = $"Failed to XmlHelper.Read({fileName})\r\n{ex.Message}\r\n{ex.StackTrace}";
  33. return null;
  34. }
  35. }
  36. public static T Read<T>(string fileContent) where T : class
  37. {
  38. try
  39. {
  40. using (var reader = new StringReader(fileContent))
  41. {
  42. XmlSerializer serializer = new XmlSerializer(typeof(T));
  43. return (serializer.Deserialize(reader) as T);
  44. }
  45. }
  46. catch (Exception ex)
  47. {
  48. return null;
  49. }
  50. }
  51. }
  52. }