/// <summary>
/// ModifyWebconfig 动态修改webconfig配置信息
/// </summary>
/// <param name="key">key</param>
/// <param name="strvalue">value</param>
/// <returns></returns>
public static void ModifyWebconfig(string key, string strvalue)
{
//string path = HttpContext.Current.Request.ApplicationPath;
//Configuration config = WebConfigurationManager.OpenWebConfiguration(path);
//AppSettingsSection appSetting = (AppSettingsSection)config.GetSection("appSettings");
//if (appSetting.Settings[key] == null)//如果不存在此节点,则添加
//{
// appSetting.Settings.Add(key, strvalue);
//}
//else//如果存在此节点,则修改
//{
// appSetting.Settings[key].Value = strvalue;
//}
//config.Save();
XmlDocument doc = new XmlDocument();
try
{
doc.Load(HttpContext.Current.Request.MapPath("web.config"));
XmlNode node;
XmlElement element;
node = doc.SelectSingleNode("//appSettings");
element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
element.SetAttribute("value", strvalue);
doc.Save(HttpContext.Current.Request.MapPath("web.config"));
}
catch (Exception)
{
}
}
/// ModifyWebconfig 动态修改webconfig配置信息
/// </summary>
/// <param name="key">key</param>
/// <param name="strvalue">value</param>
/// <returns></returns>
public static void ModifyWebconfig(string key, string strvalue)
{
//string path = HttpContext.Current.Request.ApplicationPath;
//Configuration config = WebConfigurationManager.OpenWebConfiguration(path);
//AppSettingsSection appSetting = (AppSettingsSection)config.GetSection("appSettings");
//if (appSetting.Settings[key] == null)//如果不存在此节点,则添加
//{
// appSetting.Settings.Add(key, strvalue);
//}
//else//如果存在此节点,则修改
//{
// appSetting.Settings[key].Value = strvalue;
//}
//config.Save();
//config = null;
//以上方式会将注释清除
XmlDocument doc = new XmlDocument();
try
{
doc.Load(HttpContext.Current.Request.MapPath("web.config"));
XmlNode node;
XmlElement element;
node = doc.SelectSingleNode("//appSettings");
element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
element.SetAttribute("value", strvalue);
doc.Save(HttpContext.Current.Request.MapPath("web.config"));
}
catch (Exception)
{
}
}