*** When a New Article posted, get Notification to the email that you give below: ***

Wednesday, September 10, 2014

[ C# ] - Dynamically updating the App.Config file

1. Introduction


In the last article, we saw how to use the app.config file, its hierarchy and priority in picking the application settings. In this article we will see updating the app.config file at runtime. The article example shows adding, deleting and updating a key entry the app.config file.

Have a look at the below screenshot taken from the app.config file:


The boxed item is one pair of setting; say for an example, an application by providing the key Key_4 can access the setting value value_4. In our article we are going to see how do we add, delete and update these kinds of settings that come under appSettings section of the configuration file.



2. About the example


The screenshot of the sample application is shown below:


The result of the action performed on the application configuration file (App.config) is communicated through the “Display Area”. To add (Through button Marked as 5) a setting to the application configuration file, the key and value should be entered in the Setting Key, Setting Value text boxes marked as 2 and 3 in the screen shot. To retrieve (Marked as 6) the setting, the key should be specified in the Setting Key text box. The retrieved key is displayed in the display area as well as in the Setting value. To modify (Through button marked as 7) an existing setting, specify the existing key and new modified value in the Setting Key, Setting Value respectively. To delete (Marked as 8) a key specify the key in the Setting Key. Note all these actions are performed at run time.

OK. Let us go through the coding part of this example.



3. Adding New Configuration Entry Dynamically


1) To add a new Application configuration entry, first we should make sure that the entry does not exist in the Application configuration. In the below code, first the application configuration file is opened by making a call to OpenExeConfiguration. Note that the parameter is passes is the executable file name. Then KeyValueConfigurationCollection object is retrieved from the opened configuration file through the AppSettingsSection. The reference stored in app_settings now represent the entire key, value pair of the entries that present inside the <appSettings>. To get a particular entry in the <appSettings> section, the key name is given to the collection app_settings. In our case, the value entered in the “Setting Key” text box is supplied to the app_settings to retrieve single pair that resides in <AppSettings> and if the key does not exists, a null is returned instead of a valid KeyValueConfigurationElement object. Below is the code that makes sure the setting entry exists:

//2.1 Get AppSettings section from the Config
Configuration config = ConfigurationManager.OpenExeConfiguration("ReadConStr.exe");
AppSettingsSection App_Section = (AppSettingsSection)config.GetSection("appSettings");
KeyValueConfigurationCollection app_settings = App_Section.Settings;
KeyValueConfigurationElement element = app_settings[txtKey.Text];
if (element == null)
{

2) Once we validated that the setting key is new, we allow adding a new setting entry in the application setting file. A new key-value pair element is created and added to the instance of Key-Value configuration collection. Once the collection is updated with the new entry, the application configuration file is saved to store this new entry. Below is code:

//2.2 Grab Key-Value pair & Make your Change
KeyValueConfigurationElement new_element = new KeyValueConfigurationElement(txtKey.Text, txtValue.Text);
app_settings.Add(new_element);

//2.3 Save the new appsection to App.Config
config.Save();
txtDisplayOutput.Text = "Saved";

3) Apart from this, remaining code is written to specify the result of the Action (Adding a Config. Entry). Below is entire code for adding a configuration entry:

//Sample 02: Adding application Settings to Config File
private void btnAdd_Click(object sender, EventArgs e)
{
    //2.1 Get AppSettings section from the Config
    Configuration config = ConfigurationManager.OpenExeConfiguration("ReadConStr.exe");
    AppSettingsSection App_Section = (AppSettingsSection)config.GetSection("appSettings");
    KeyValueConfigurationCollection app_settings = App_Section.Settings;
    KeyValueConfigurationElement element = app_settings[txtKey.Text];
    if (element == null)
    {
        //2.2 Grab Key-Value pair & Make your Change
        KeyValueConfigurationElement new_element = new KeyValueConfigurationElement(txtKey.Text, txtValue.Text);
        app_settings.Add(new_element);

        //2.3 Save the new appsection to App.Config
        config.Save();
        txtDisplayOutput.Text = "Saved";
    }
    else
    {
        txtDisplayOutput.Text = "Key Already Exists";
    }

    //2.4 Clean up
    txtKey.Text = "";
    txtValue.Text = "";
}



4. Retrieving the Configuration Entry without re-starting


When an application setting is added dynamically it can be retrieved dynamically. The code below retrieves the newly added application entry without re-launching the application again. Here we check that the key entry already exists in the application configuration file and if so, we display the corresponding value in the Display Area.

//Sample 03: Read Application settings
private void btnAppSettings_Click(object sender, EventArgs e)
{
    //3.1 Get AppSettings section from the Config
    Configuration config = ConfigurationManager.OpenExeConfiguration("ReadConStr.exe");
    AppSettingsSection App_Section = (AppSettingsSection)config.GetSection("appSettings");
    KeyValueConfigurationCollection app_settings = App_Section.Settings;

    //3.2 Retrieve Specific element by Key and Display it
    KeyValueConfigurationElement element = app_settings[txtKey.Text];
    if (element != null)
    {
        txtDisplayOutput.Text = element.Value;
        txtValue.Text = element.Value;
    }
    else
    {
        txtDisplayOutput.Text = "Setting Not found";
    }
}



5. Modifying the application configuration Entry


To modify the key-value pair in the application configuration, grab the key value pair, remove it and add the new one. In the below code we search for the specific key, grab the configuration entry and drop it. Then, a new entry with the same key name and modified value is pushed into the application configuration collection. As the code is similar to what you learned already, I am skipping the further explanation here. Below is the complete code for modifying the configuration entry:

//Sample 04: Modify Application Settings
private void btnModify_Click(object sender, EventArgs e)
{
    //4.1 Get AppSettings section from the Config
    Configuration config = ConfigurationManager.OpenExeConfiguration("ReadConStr.exe");
    AppSettingsSection App_Section = (AppSettingsSection)config.GetSection("appSettings");
    KeyValueConfigurationCollection app_settings = App_Section.Settings;
    KeyValueConfigurationElement element = app_settings[txtKey.Text];

    //4.2 Grab Key-Value pair & Make your Change
    if (element != null)
    {
        element.Value = txtValue.Text;
        app_settings.Remove(txtKey.Text);
        app_settings.Add(element);

        //4.3 Save the new appsection to App.Config
        config.Save();
        txtDisplayOutput.Text = "Setting Modified";
    }
    else
    {
        txtDisplayOutput.Text = "Setting Not Found";
    }

    //4.4 Clean up
    txtKey.Text = "";
    txtValue.Text = "";
}

6. Deleting the application configuration Entry


By this time, you may be aware how to do this. Yes, similar to previous section code except after dropping the configuration section we save the configuration file.

//Sample 05: Delete Application Settings
private void btnDelete_Click(object sender, EventArgs e)
{
    //5.1 Get AppSettings section from the Config
    Configuration config = ConfigurationManager.OpenExeConfiguration("ReadConStr.exe");
    AppSettingsSection App_Section = (AppSettingsSection)config.GetSection("appSettings");
    KeyValueConfigurationCollection app_settings = App_Section.Settings;
    KeyValueConfigurationElement element = app_settings[txtKey.Text];

    //5.2 Remove the setting by Key
    if (element != null)
    {
        app_settings.Remove(txtKey.Text);
        config.Save();
        txtDisplayOutput.Text = "Setting Removed";
    }
    else
    {
        txtDisplayOutput.Text = "Setting Not Found";
    }

    //5.4 Clean up
    txtKey.Text = "";
    txtValue.Text = "";
}


The video given below show how the Example application works:


Source Code : Download

C++ Articles

DISCLAIMER

The opinions expressed herein are my own personal opinions and do not represent my current or previous employer's view in anyway