This function mainly uses XmlDocument to parse web. config. and uses the SelectSingleNode () method to locate the configuration section to be modified. Note that the last program must be saved (). Therefore, your apsnet account must have write permission on web. config.
--------------------------------------------------------------------------------
/// <Summary>
/// Modify the value Attribute in Add in the configuration section of the web. config file appSettings.
/// </Summary>
/// <Remarks>
/// Note: after this function is called, the entire Web Application will be restarted, resulting in the loss of all sessions currently
/// </Remarks>
/// <Param name = "key"> key to be modified </param>
/// <Param name = "strValue"> modified value </param>
/// <Exception cref = ""> related keys cannot be found </exception>
/// <Exception cref = ""> the permission is insufficient and cannot be saved to the web. config file. </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 ("configuration section of <add key = '" + key + "'value =.../> not found ");
}
AddKey. Attributes ["value"]. InnerText = strValue;
DomWebConfig. Save (HttpContext. Current. Server. MapPath ("web. config ")));
}