Search code examples
c#web-config

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


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.


Solution

  • 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.