使用C#(.NET)以编程方式更改web.config

我怎样才能修改/操作web.config编程与C#? 我可以使用一个configuration对象,如果是的话,我怎样才能加载web.config到configuration对象? 我想有一个完整的例子改变连接string。 修改后, web.config应该写回硬盘。

这里是一些代码:

 var configuration = WebConfigurationManager.OpenWebConfiguration("~"); var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings"); section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=..."; configuration.Save(); 

请参阅本文中的更多示例,您可能需要查看模拟 。

 Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection; //section.SectionInformation.UnprotectSection(); section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider"); config.Save(); 

由于web.config文件是xml文件,因此可以使用xmldocument类打开web.config。 从要更新的xml文件中获取节点,然后保存xml文件。

这里是更详细地解释如何以编程方式更新web.config文件的URL。

http://patelshailesh.com/index.php/update-web-config-programmatically

注意:如果您对web.config进行了任何更改,ASP.NET会检测到更改并重新加载应用程序(回收应用程序池),并且会影响Session,Application和Cache中保存的数据(假设会话状态是InProc,不使用状态服务器或数据库)。