AppSettings.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Xml;
  6. using System.Windows.Forms;
  7. namespace Falit.Run
  8. {
  9.     /// <summary>
  10.     /// App.config配置类
  11.     /// </summary>
  12.     public class AppSettings
  13. {
  14.         /// <summary>
  15.         /// 获取配置文件路径
  16.         /// </summary>
  17.         /// <returns></returns>
  18.         public static string AppConfig()
  19. {
  20. return System.IO.Path.Combine(Application.StartupPath, "App.config");
  21.         }
  22.         /// <summary>
  23.         /// 获取配置节点值
  24.         /// </summary>
  25.         /// <param name="appKey">节点key值</param>
  26.         /// <returns></returns>
  27.         public static string GetValue(string appKey)
  28. {
  29. XmlDocument xDoc = new XmlDocument();
  30. try
  31. {
  32. xDoc.Load(AppSettings.AppConfig());
  33. XmlNode xNode;
  34. XmlElement xElem;
  35. xNode = xDoc.SelectSingleNode("//appSettings");   
  36.                 xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']");
  37. if (xElem != null)
  38. return xElem.GetAttribute("value");
  39. else
  40. return "";
  41. }
  42. catch (Exception)
  43. {
  44. return "";
  45. }
  46. }
  47.         /// <summary>
  48.         /// 设置配置节点值
  49.         /// </summary>
  50.         /// <param name="AppKey">key</param>
  51.         /// <param name="AppValue">value</param>
  52.         public static void SetValue(string AppKey, string AppValue)
  53. {
  54. XmlDocument xDoc = new XmlDocument();
  55. xDoc.Load(AppSettings.AppConfig());
  56. XmlNode xNode;
  57. XmlElement xElem1;
  58. XmlElement xElem2;
  59. xNode = xDoc.SelectSingleNode("//appSettings");
  60. xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
  61. if (xElem1 != null)
  62. {
  63. xElem1.SetAttribute("value", AppValue);
  64. }
  65. else
  66. {
  67. xElem2 = xDoc.CreateElement("add");
  68. xElem2.SetAttribute("key", AppKey);
  69. xElem2.SetAttribute("value", AppValue);
  70. xNode.AppendChild(xElem2);
  71. }
  72. xDoc.Save(AppSettings.AppConfig());
  73. }
  74. }
  75. }