C#: Modify App.config file at run time

Posted: 17 October, 2011 in C#

Web.Config in web applications and App.Config in the desktop application can come very handy to store and retrieve different configuration / user variables or settings. Reading from the config files is very easy:

ConfigurationManager.AppSettings["Category"];

However modifying config file will take extra lines of code. Below lines will update the key attribute by deleting previous entry and adding new entry in the config file:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove(“Category”);
config.AppSettings.Settings.Add(“Category”, “New Value”);
config.Save(ConfigurationSaveMode.Modified);

Note: You will need to add reference to System.Configuration namespace (using System.Configuration)
Also this will not work while debugging from Visual Studio. Run the .exe file from Release or Debug folder and it should work perfectly.

Source

Comments
  1. David says:

    Excellent

  2. Lau says:

    Hi,

    what about if I want to reload the app.config from the phisical file? not just the one in memory?

    Thx Laura

  3. gunjan says:

    the code is running fine but I the changes are not visible in app.config during debug.

    • SufianRashid says:

      yes i also mentioned it in my post; that it will not work during debug.
      the reason being is the web.config/app.config that you are viewing is visual studio is not what is currently being used in execution.

      Instead all necessary files are copied in Bin/Release or Bin/Debug folder and executed from there. so you need to look at correct file to see the changes.

      • Gunjan Arora says:

        thanks for reply but still I am facing the problem that the changes are temporary upto when the win app is running.I want something that makes permanent changes in app config when i update connection string from win form.

  4. Dhaval says:

    Can I Change Connection String After Create Setup or Deploy or Publish XBAP Application ??

    • SufianRashid says:

      I am not sure about that; do you mean to add new connection string or just select one of multiple connection string already provided in the configuration files?

      If you meant adding a new connection string which doesn’t exist in app.config/web.config file after deployment/setup is created; then i believe it will be difficult if the output is a single binary file. But there may be some tools that can do this for you. Try searching them.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s