2010-09-15 56 views
0

是否有可能在運行時更改web.config的內容?動態操作配置文件

+1

可能重複[你如何在運行時修改web.config中的appSettings?](http://stackoverflow.com/questions/719928/how-do-you-modify-the-web-config-的AppSettings-在運行時) – M4N 2010-09-15 08:43:04

回答

0

使用WebConfigurationManager類的另一種方法。

Configuration cfg = WebConfigurationManager.OpenWebConfiguration("~"); 
ConnectionStringSettings consettings = cfg.ConnectionStrings.ConnectionStrings["conkey"]; 
consettings.ConnectionString = "updated value";   
cfg.Save(); 
0

我試過以下代碼來在運行時更新web.config文件。

比方說web.config中有這樣

<connectionStrings> 
    <add name="conkey" connectionString="old value" /> 
</connectionStrings> 

的關鍵,這裏是C#代碼更新web.config文件。

string path = Server.MapPath("Web.config"); 
      string newConnectionString = "updated value"; // Updated Value 

      XmlDocument xDoc = new XmlDocument(); 
      xDoc.Load(path); 

      XmlNodeList nodeList = xDoc.GetElementsByTagName("connectionStrings"); 

      XmlNodeList nodeconnectionStrings = nodeList[0].ChildNodes; 

      XmlAttributeCollection xmlAttCollection = nodeconnectionStrings[0].Attributes; 

      xmlAttCollection[1].InnerXml = newConnectionString; // for value attribute 

      xDoc.Save(path); // saves the web.config file 

此代碼適用於我。不過建議不要這樣做。