asp.net中动态修改配置文件的方法


  众多时候,我们可能会在asp.net中动态的 批改配置文件,我们 可以 使用如下代码中 波及到的类来 实现配置文件,下面的代码是 批改connectionstring的例子:

  System.Configuration.Configuration c = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("'");

  c.ConnectionStrings.ConnectionStrings.Clear();

  ConnectionStringSettings s = new ConnectionStringSettings();

  s.ProviderName = "System.Data.OleDb";

  s.ConnectionString = "Provider=Microsoft.oledb.jet.4.0;data source=c:\\abc.mdb";

  s.Name = "myaccess";

  c.ConnectionStrings.ConnectionStrings.Add(s);

  c.Save();

  然而asp.net由于安全性的关系, 不同意用Configuration的类对Web.config进行 批改,

  不得不用操作xml对象的 模式进行 批改

  XmlDocument doc = new XmlDocument();

  doc.Load("Web.config");

  XmlNode node = doc.DocumentElement.SelectSingleNode("appSettings");

  node.SelectSingleNode("descendant::add[@key='Value_Inform']") 。Attributes[1].Value = "111";

  doc.DocumentElement.SelectSingleNode("appSettings") 。InnerXml = node.InnerXml;

  doc.Save("Web.config");

  尽量不要 批改web.config文件

  web.config的 改变由aspnet_wp 历程 监督,假如有 改变,由于会招致web 利用程序重启,减低性能,全部的Session会重置

  然而不 提议动态 批改web.config的值,由于会招致web 利用程序重启,减低性能 。