Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

web-config

How can I modify / manipulate the web.config programmatically with C# ? Can I use a configuration object, and, if yes, how can I load the web.config into a configuration object ? I would like to have a full example changing the connection string. After the modification the web.config should be written back to the harddisk.

like image 858
Kottan Avatar asked Feb 14 '10 06:02

Kottan


People also ask

Can we update Web config settings programmatically?

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

Does machine config override Web config?

The machine. config file file is at the highest level in the configuration hierarchy while Web. config file is to override the settings from the machine. config file.


1 Answers

Here it is some code:

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

See more examples in this article, you may need to take a look to impersonation.

like image 139
Alex LE Avatar answered Oct 14 '22 05:10

Alex LE