一个修改web.config中appSettings配置节的函数

这个函数主要使用XmlDocument来解析web.config.并用SelectSingleNode()方法来定位要修改的配置节。要注意的是最后程序要Save(),所以,你的apsnet帐号必须对web.config拥有写权限.


///

1<summary>   
2/// 修改web.config文件appSettings配置节中的Add里的value属性   
3/// </summary>

///

1<remarks>   
2/// 注意,调用该函数后,会使整个Web Application重启,导致当前所有的会话丢失   
3/// </remarks>

///

1<param name="key"/>

要修改的键key
///

1<param name="strValue"/>

修改后的value
///

1<exception cref="">找不到相关的键</exception>

///

1<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("没有找到

1<add key='"+key+"' value=".../">的配置节");   
2}   
3addKey.Attributes["value"].InnerText=strValue;   
4domWebConfig.Save( (HttpContext.Current.Server.MapPath("web.config")) );   
5  
6}</add>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus