C# 获取 与 修改 web.config中的值(修改Xml文件)
定义web.config 中 appSettings 节点
<appSettings> <add key="domainExist" value="false"></add> </appSettings>
获取
string domainExist = ConfigurationManager.AppSettings["domainExist"];
修改并刷新
UpdAppSettings("domainExist", "true"); ConfigurationManager.RefreshSection("appSettings"); /// <summary> /// 修改web.config中appSettings键的值 /// </summary> /// <param name="keyName">键的名称</param> /// <param name="keyValue">键的值</param> public static void UpdAppSettings( string keyName, string keyValue) { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); try { //获取 Web.config 的路径 string configPath = HttpRuntime.AppDomainAppPath.ToString()+"Web.config"; doc.Load(configPath); System.Xml.XmlNode node; System.Xml.XmlElement element; node = doc.SelectSingleNode("//appSettings"); element = (System.Xml.XmlElement)node.SelectSingleNode("//add[@key='" + keyName + "']"); if (element != null) { element.SetAttribute("value", keyValue); doc.Save(configPath); } } catch (Exception) { throw; } }