The structure of an application’s configuration file always include:

  1. The root node: start with and end with
  2. Configuation sections, connectionStrings, appSettings, custom defined sections, etc.

Of course, we can update the configuration sections mannually, the values defined in the configuration file are always stable and seems will never be changed, but we may still need to update the configuration values dynamically in some special cases.

First, let’s take a look at the class Configuration under System.Configuration namespace:

System.Configuration.Configuration

Take property ConnectionStrings as an example, it is of type ConnectionStringsSection, then we follow the type, to see the members of the ConnectionStringsSection:

System.Configuration.ConnectionStringsSection

OK, from the picture, we can see that the property ConnectionStrings is of type ConnectionStringSettingsCollection, the collection? if it is a collection, will it has methods like Add() or Remove()? then if we go to the defination of ConnectionStringSettingsCollection, definately we will find two methods:
public void Add(ConnectionStringSettings settings);
public void Remove(ConnectionStringSettings settings);
Then, if we want to add/remove a connection string from the configuration file, we will use these two methods, look at the code below:
1:  public static void SaveConnectionString(string name, string connectionString)
2:  {
3:   Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
4:   if (config.ConnectionStrings.ConnectionStrings[name] == null)
5:   {
6:   config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(name,
connectionString));
7:   }
8:   else
9:   {
10:   config.ConnectionStrings.ConnectionStrings[name].ConnectionString = connectionString;
11:   }
12:
13:   config.Save(ConfigurationSaveMode.Modified);
14:
15:   ConfigurationManager.RefreshSection(“connectionStrings”);
16:  }
line 3, we use the ConfigurationManager to open the configuration file of the current application.
line 13, after we created/updated the connection string in memory, we need to save the changes to the configuration file.
line 15, use the RefreshSection(string sectionName) method to fore the current application to reload the specified section, this is important, if you don’t so this, the changes won’t affect before you restart the application.
In the same way, we can create/update appSettings dynamically:
1:  public static void SaveSetting(string key, string value)
2:  {
3:   Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
4:   if (config.AppSettings.Settings[key] == null)
5:   {
6:   config.AppSettings.Settings.Add(key, value);
7:   }
8:   else
9:   {
10:   config.AppSettings.Settings[key].Value = value;
11:   }
12:
13:   config.Save(ConfigurationSaveMode.Modified);
14:   ConfigurationManager.RefreshSection(“appSettings”);
15:  }
Extra Q&A:
Q: How to create/update a custom defined section?
A: Use the config.Sections.Add(…) method.
Q: How to create/update a node in a custom defined section?
A: Use the config.GetSection(“custom section name”) or config.Section[“custom section name”] to get the custom section first, and then do the same as connectionStrings or appSettings.
NOTE: it is important to call ConfigurationManager.RefreshSection(“section name”) to make the changes work immediatelly.

OK, from the picture, we can see that the property ConnectionStrings is of type ConnectionStringSettingsCollection, the collection? if it is a collection, will it has methods like Add() or Remove()? then if we go to the defination of ConnectionStringSettingsCollection, definately we will find two methods:

  • public void Add(ConnectionStringSettings settings);
  • public void Remove(ConnectionStringSettings settings);

Then, if we want to add/remove a connection string from the configuration file, we will use these two methods, look at the code below:

  public static void SaveConnectionString(string name, string connectionString)
  {
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        if (config.ConnectionStrings.ConnectionStrings[name] == null)
        {
               config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(name, connectionString));
         }
         else
         {
              config.ConnectionStrings.ConnectionStrings[name].ConnectionString = connectionString;
        }

        config.Save(ConfigurationSaveMode.Modified);

        ConfigurationManager.RefreshSection("connectionStrings");
  }

line 3, we use the ConfigurationManager to open the configuration file of the current application.
line 13, after we created/updated the connection string in memory, we need to save the changes to the configuration file.
line 15, use the RefreshSection(string sectionName) method to fore the current application to reload the specified section, this is important, if you don’t so this, the changes won’t affect before you restart the application.

In the same way, we can create/update appSettings dynamically:

 public static void SaveSetting(string key, string value)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] == null)
{
               config.AppSettings.Settings.Add(key, value);
        }
        else
        {
             config.AppSettings.Settings[key].Value = value;
       }

       config.Save(ConfigurationSaveMode.Modified);
       ConfigurationManager.RefreshSection("appSettings");
  }
Extra Q&A:

Q: How to create/update a custom defined section?
A: Use the config.Sections.Add(…) method.
Q: How to create/update a node in a custom defined section?
A: Use the config.GetSection(“custom section name”) or config.Section[“custom section name”] to get the custom section first, and then do the same as connectionStrings or appSettings.

NOTE: it is important to call ConfigurationManager.RefreshSection(“section name”) to make the changes work immediately.

相关文章:

  1. DotNet下NUnit的使用(1)—- NUnit入门
  2. DotNet下NUnit的使用(2)—- 第一个NUnit工程
  3. 性能: 字符串倒序算法 (C# version)
  4. 使用InternalsVisibleTo给assembly添加“友元assembly”
  5. 在.NET项目中使用log4net
  6. How to use Sql Azure