UserConfigXML.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Xml.Linq;
  7. using System.Xml.Serialization;
  8. namespace SiwiFms.Helper
  9. {
  10. public class UserConfigXML
  11. {
  12. public static readonly UserConfigXML Instance = new UserConfigXML();
  13. private string filePath;
  14. private List<UserProfie> userProfies = new List<UserProfie>();
  15. private UserConfigXML()
  16. {
  17. filePath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "UserConfig.xml");
  18. LoadUserConfigXML();
  19. }
  20. /// <summary>
  21. /// 获取指定key的值
  22. /// </summary>
  23. /// <param name="key"></param>
  24. /// <returns></returns>
  25. public string ReadSetting(string key)
  26. {
  27. var up = userProfies.FirstOrDefault(m => m.Key == key);
  28. if (up != null)
  29. return up.Value;
  30. else
  31. return string.Empty;
  32. }
  33. /// <summary>
  34. /// 添加一个配置
  35. /// </summary>
  36. /// <param name="key"></param>
  37. /// <param name="value"></param>
  38. public void WriteSetting(string key, string value)
  39. {
  40. var us = userProfies.FirstOrDefault(m => m.Key == key);
  41. if (us != null)
  42. userProfies.Remove(us);
  43. userProfies.Add(new UserProfie { Key = key, Value = value });
  44. SaveUserConfigXML();
  45. }
  46. /// <summary>
  47. /// 删除一个配置
  48. /// </summary>
  49. /// <param name="key"></param>
  50. public void RemoveSetting(string key)
  51. {
  52. var us = userProfies.FirstOrDefault(m => m.Key == key);
  53. if (us != null)
  54. {
  55. userProfies.Remove(us);
  56. SaveUserConfigXML();
  57. }
  58. }
  59. /// <summary>
  60. /// 保存配置
  61. /// </summary>
  62. private void SaveUserConfigXML()
  63. {
  64. try
  65. {
  66. var domLinq = new XElement("AppSettings",from c in userProfies
  67. select new XElement("add",new XAttribute("key",c.Key),new XAttribute("value",c.Value)));
  68. domLinq.Save(filePath);
  69. }
  70. catch(Exception ex)
  71. {
  72. Console.WriteLine(ex.Message);
  73. }
  74. }
  75. /// <summary>
  76. /// 获取配置文件地址
  77. /// </summary>
  78. private void LoadUserConfigXML()
  79. {
  80. if (File.Exists(filePath))
  81. {
  82. try
  83. {
  84. XmlSerializer xs = new XmlSerializer(typeof(List<UserProfie>));
  85. using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
  86. {
  87. userProfies = (List<UserProfie>)xs.Deserialize(fs);
  88. }
  89. }
  90. catch(Exception ex)
  91. {
  92. Console.WriteLine(ex.Message);
  93. }
  94. }
  95. }
  96. }
  97. public class UserProfie
  98. {
  99. public string Key { get; set; }
  100. public string Value { get; set; }
  101. }
  102. }