商丘12345对接新点

ConfigHelper.cs 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Configuration;
  3. using System.IO;
  4. using System.Web;
  5. using System.Xml;
  6. namespace SQ12345_OutApi.Utility
  7. {
  8. public class ConfigHelper
  9. {
  10. static XmlDocument xDoc;
  11. static XmlNode xNode;
  12. static ConfigHelper()
  13. {
  14. lasttime = new FileInfo(path).LastWriteTime;
  15. xDoc = new XmlDocument();
  16. xDoc.Load(path);
  17. xNode = xDoc.SelectSingleNode("//appSettings");
  18. }
  19. static string path = HttpContext.Current.Server.MapPath("~/Configs/system.config");
  20. static DateTime lasttime = DateTime.Now;
  21. /// <summary>
  22. /// 根据Key取Value值
  23. /// </summary>
  24. /// <param name="key"></param>
  25. public static string GetValue(string key)
  26. {
  27. try
  28. {
  29. DateTime dt = new FileInfo(path).LastWriteTime;
  30. if (dt != lasttime)
  31. {
  32. xDoc = new XmlDocument();
  33. xDoc.Load(path);
  34. xNode = xDoc.SelectSingleNode("//appSettings");
  35. lasttime = dt;
  36. }
  37. var xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + key + "']");
  38. return xElem1?.GetAttribute("value") ?? "";
  39. }
  40. catch
  41. {
  42. return "";
  43. }
  44. }
  45. /// <summary>
  46. /// 根据Key修改Value
  47. /// </summary>
  48. /// <param name="key">要修改的Key</param>
  49. /// <param name="value">要修改为的值</param>
  50. public static void SetValue(string key, string value)
  51. {
  52. try
  53. {
  54. DateTime dt = new FileInfo(path).LastWriteTime;
  55. if (dt != lasttime)
  56. {
  57. xDoc = new XmlDocument();
  58. xDoc.Load(path);
  59. xNode = xDoc.SelectSingleNode("//appSettings");
  60. lasttime = dt;
  61. }
  62. XmlElement xElem1;
  63. XmlElement xElem2;
  64. xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + key + "']");
  65. if (xElem1 != null) xElem1.SetAttribute("value", value);
  66. else
  67. {
  68. xElem2 = xDoc.CreateElement("add");
  69. xElem2.SetAttribute("key", key);
  70. xElem2.SetAttribute("value", value);
  71. xNode.AppendChild(xElem2);
  72. }
  73. xDoc.Save(path);
  74. }
  75. catch
  76. { }
  77. }
  78. }
  79. }