一個修改web.config中appSettings配置節的函數
來源:互聯網
上載者:User
web|函數 這個函數主要使用XmlDocument來解析web.config.並用SelectSingleNode()方法來定位要修改的配置節。要注意的是最後程式要Save(),所以,你的apsnet帳號必須對web.config擁有寫入權限.
--------------------------------------------------------------------------------
/// <summary>
/// 修改web.config檔案appSettings配置節中的Add裡的value屬性
/// </summary>
/// <remarks>
/// 注意,調用該函數後,會使整個Web Application重啟,導致當前所有的會話丟失
/// </remarks>
/// <param name="key">要修改的鍵key</param>
/// <param name="strValue">修改後的value</param>
/// <exception cref="">找不到相關的鍵</exception>
/// <exception cref="">許可權不夠,無法儲存到web.config檔案中</exception>
public void Modify(string key,string strValue)
{
string XPath="/configuration/appSettings/add[@key='?']";
XmlDocument domWebConfig=new XmlDocument();
domWebConfig.Load( (HttpContext.Current.Server.MapPath("web.config")) );
XmlNode addKey=domWebConfig.SelectSingleNode( (XPath.Replace("?",key)) );
if(addKey == null)
{
throw new ArgumentException("沒有找到<add key='"+key+"' value=.../>的配置節");
}
addKey.Attributes["value"].InnerText=strValue;
domWebConfig.Save( (HttpContext.Current.Server.MapPath("web.config")) );
}