往配置文件中保存配置信息
View Code
1 public void SetConfigValue(string AppKey, string AppValue) 2 { 3 XmlDocument xDoc = new XmlDocument(); 4 xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config"); 5 XmlNode xNode; 6 XmlElement xElem1; 7 XmlElement xElem2; 8 xNode = xDoc.SelectSingleNode("//appSettings"); 9 xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']"); 10 if (xElem1 != null) 11 xElem1.SetAttribute("value", AppValue); 12 else//如果没有该节点,则添加 13 { 14 xElem2 = xDoc.CreateElement("add"); 15 xElem2.SetAttribute("key", AppKey); 16 xElem2.SetAttribute("value", AppValue); 17 xNode.AppendChild(xElem2); 18 } 19 xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config"); 20 }
根据节点名称读取配置信息
View Code
1 public string GetConfigValue(string AppKey) 2 { 3 XmlDocument xDoc = new XmlDocument(); 4 try 5 { 6 xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config"); 7 XmlNode xNode = xDoc.SelectSingleNode("//appSettings"); 8 XmlElement xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']"); 9 if (xElem != null) 10 return xElem.GetAttribute("value"); 11 else 12 return ""; 13 } 14 catch (Exception ex) 15 { 16 return ex.ToString(); 17 } 18 }