AppConfig.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System.IO;
  2. using System.Xml;
  3. namespace LJLib.Tools.File
  4. {
  5. public static class AppConfig
  6. {
  7. /// <summary>
  8. /// 设置xml值
  9. /// </summary>
  10. /// <param name="xmlPath">xml文件名</param>
  11. /// <param name="keyname">值名</param>
  12. /// <param name="value">取值</param>
  13. public static void SetXmlFileValue(string xmlPath, string keyname, string value)
  14. {
  15. FileStream file = System.IO.File.Open(xmlPath, FileMode.OpenOrCreate);
  16. XmlDocument xDoc = new XmlDocument();
  17. try
  18. {
  19. xDoc.Load(file);
  20. }
  21. catch (System.Exception)
  22. {
  23. xDoc.LoadXml("<configuration/>");
  24. }
  25. file.Close();
  26. XmlNode xRoot = xDoc.DocumentElement;
  27. XmlElement xSection = (XmlElement)xRoot.SelectSingleNode("appSettings");
  28. if (xSection == null)
  29. {
  30. xSection = xDoc.CreateElement("appSettings");
  31. xRoot.AppendChild(xSection);
  32. }
  33. XmlElement xElem = (XmlElement)xSection.SelectSingleNode("add[@key='" + keyname + "']");
  34. if (xElem != null)
  35. {
  36. xElem.SetAttribute("value", value);
  37. }
  38. else
  39. {
  40. XmlElement xTmpElem = xDoc.CreateElement("add");
  41. xTmpElem.SetAttribute("key", keyname);
  42. xTmpElem.SetAttribute("value", value);
  43. xSection.AppendChild(xTmpElem);
  44. }
  45. xDoc.Save(xmlPath);
  46. }
  47. /// <summary>
  48. /// 读取xml值
  49. /// </summary>
  50. /// <param name="xmlPath"></param>
  51. /// <param name="keyname"></param>
  52. /// <param name="defaultValue"></param>
  53. /// <returns></returns>
  54. public static string GetXmlFileValue(string xmlPath, string keyname, string defaultValue)
  55. {
  56. if (!System.IO.File.Exists(xmlPath))
  57. {
  58. return defaultValue;
  59. }
  60. FileStream file = System.IO.File.OpenRead(xmlPath);
  61. XmlDocument xDoc = new XmlDocument();
  62. try
  63. {
  64. xDoc.Load(file);
  65. }
  66. catch (System.Exception)
  67. {
  68. xDoc.LoadXml("<configuration/>");
  69. }
  70. file.Close();
  71. XmlNode xRoot = xDoc.DocumentElement;
  72. XmlElement xSection = (XmlElement)xRoot.SelectSingleNode("appSettings");
  73. if (xSection == null)
  74. {
  75. return defaultValue;
  76. }
  77. XmlElement xElem = (XmlElement)xSection.SelectSingleNode("add[@key='" + keyname + "']");
  78. if (xElem == null)
  79. {
  80. return defaultValue;
  81. }
  82. else
  83. {
  84. return xElem.GetAttribute("value");
  85. }
  86. }
  87. }
  88. }