Change web.config programmatically with C # (.NET)

How can I modify / manage web.config software using C #? Can I use the configuration object, and if so, how can I load web.config into the configuration object? I would like to have a complete example of changing a connection string. After changing web.config , write it back to your hard drive.

+74
c # web-config
Feb 14 '10 at 6:22
source share
3 answers

Here is the code:

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

For more details in this article , you may need to take a look at avatars .

+94
Feb 14 '10 at 6:28
source share
 Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection; //section.SectionInformation.UnprotectSection(); section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider"); config.Save(); 
+11
Feb 14 '10 at 19:34
source share

Since the web.config file is an xml file, you can open web.config using the xmldocument class. Get the node from this xml file you want to update, and then save the xml file.

Here is a URL that explains in more detail how to programmatically update the web.config file.

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

Note: if you make any changes to web.config, ASP.NET will detect these changes and restart your application (pool of repeated application pools), and the effect of this will depend on the data stored in the session, application and cache (assuming that the session state is InProc and does not use a public server or database).

+5
Feb 17 '10 at 20:11
source share



All Articles