98

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.

Jaime Marín
  • 578
  • 6
  • 11
Kottan
  • 4,944
  • 9
  • 41
  • 67
  • Check his blog post about how to [Programmatically manipulating web.config in ASP.NET 2.0 and ASP.NET 3.5](http://www.dotnetcurry.com/ShowArticle.aspx?ID=102) Alternatively check this question which has the answer for your question. [How do I set a connection string config programatically in .net?](http://stackoverflow.com/questions/360024/how-do-i-set-a-connection-string-config-programatically-in-net/1312739) – Shoban Feb 14 '10 at 06:27

4 Answers4

122

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.

Alex LE
  • 20,042
  • 4
  • 30
  • 28
  • What is the name of your connection string in the web.config file? – Alex LE Oct 25 '12 at 18:14
  • link to article is broken – Vitall Feb 21 '14 at 09:27
  • @AlexLE: How do we specify the file location when web.config is placed at a different location. May be a remote server on a shared path? – SharpCoder Jun 24 '16 at 15:46
  • @SharpCoder, the path is a virtual path, so you need first copy the web.config from the remote server to your local application (inside a temp folder to not override your own web.config) ,edit it, save and then copy back to the remote server. Or a better, more complex solution would be: create a API that does de job (change de web.config), deploy it to the remote server and then consume it from local server. – Guilherme Branco Stracini Oct 10 '16 at 14:09
  • @Skami you must be set connectionStrings name to "MyConnectionString" thats means section.ConnectionStrings["MyConnectionString"] value should match with name. – Liakat Hossain Mar 04 '19 at 04:55
  • 2
    It's been a long time but does this modification make the app pool recycle? – ibubi May 26 '21 at 11:24
12
Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
//section.SectionInformation.UnprotectSection();
section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
config.Save();
Terrance
  • 11,764
  • 4
  • 54
  • 80
ASergan
  • 171
  • 8
6

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.

here is URL that explains in more detail how you can update web.config file programmatically.

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

Note: if you make any changes to web.config, ASP.NET detects that changes and it will reload your application(recycle application pool) and effect of that is data kept in Session, Application, and Cache will be lost (assuming session state is InProc and not using a state server or database).

shailesh
  • 5,013
  • 5
  • 23
  • 22
  • I know that it is technically possible, I think the method sanctioned / approved by Microsoft is likely to be longer lasting and less subject to breaking the web.config. We have all updated these files "by hand", but I think it is risky with production web servers. Just my 2c. – Anthony Horne Jul 13 '18 at 05:10
2

This is a method that I use to update AppSettings, works for both web and desktop applications. If you need to edit connectionStrings you can get that value from System.Configuration.ConnectionStringSettings config = configFile.ConnectionStrings.ConnectionStrings["YourConnectionStringName"]; and then set a new value with config.ConnectionString = "your connection string";. Note that if you have any comments in the connectionStrings section in Web.Config these will be removed.

private void UpdateAppSettings(string key, string value)
{
    System.Configuration.Configuration configFile = null;
    if (System.Web.HttpContext.Current != null)
    {
        configFile =
            System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
    }
    else
    {
        configFile =
            ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    }
    var settings = configFile.AppSettings.Settings;
    if (settings[key] == null)
    {
        settings.Add(key, value);
    }
    else
    {
        settings[key].Value = value;
    }
    configFile.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
}
Ogglas
  • 62,132
  • 37
  • 328
  • 418
  • 1
    This code is good and I upvoted it, but it won't work if the appSettings is defined in another file, like for example: – Ben Junior May 26 '19 at 21:12