Click here to Skip to main content
15,881,715 members
Articles / Programming Languages / Visual Basic

Change .config File at Runtime C# Code

Rate me:
Please Sign up or sign in to vote.
4.71/5 (14 votes)
22 Feb 2015CPOL2 min read 52.7K   22   1
How to change .config file at runtime (C# VB.NET code)

Introduction

At times, you may need to modify the configuration files for your application at runtime. I have developed a generic class – “ConfigModificator” for the purpose. I will share the code with you and explain how to use it.

How to use the “ConfigModificator” to change .config Files at Runtime

First, you need to initialize a settings object of type ConfigModificatorSettings. It contains only three properties.

C#
public class ConfigModificatorSettings
    {
        public string RootNode { get; set; }
        public string NodeForEdit { get; set; }
        public string ConfigPath { get; set; }
    }

If we have an app.config file with the following structure:

XML
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="testKey " value="1" />
    <add key="testKey1" value="myTestValue" />
  </appSettings>
</configuration>

We use the following settings object:

C#
string appConfigFilePath = 
   string.Concat(Assembly.GetExecutingAssembly().Location, ".config");
ConfigModificatorSettings appConfigWriterSettings = 
   new ConfigModificatorSettings
   ("//appSettings", "//add[@key='{0}']", appConfigFilePath);

We use reflection to get the current assembly’s name and location. That is how the app.config file path is generated.

  • //appSettings – is our RootNode
  • //add[@key='{0}’] – is the NodeForEditProperty

There are the two core methods of the ConfigModificator which we are going to use to change .config files values.

C#
public static void ChangeValueByKey
(string key, string value, string attributeForChange,
ConfigModificatorSettings configWriterSettings)
    {
        XmlDocument doc = ConfigModificator.LoadConfigDocument(configWriterSettings.ConfigPath);
        XmlNode rootNode = doc.SelectSingleNode(configWriterSettings.RootNode);

        if (rootNode == null)
        {
            throw new InvalidOperationException("the root node section not found in config file.");
        }

        try
        {
            XmlElement elem = (XmlElement)rootNode.SelectSingleNode
                            (string.Format(configWriterSettings.NodeForEdit, key));
            elem.SetAttribute(attributeForChange, value);
            doc.Save(configWriterSettings.ConfigPath);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private static XmlDocument LoadConfigDocument(string configFilePath)
    {
        XmlDocument doc = null;
        try
        {
            doc = new XmlDocument();
            doc.Load(configFilePath);
            return doc;
        }
        catch (System.IO.FileNotFoundException e)
        {
            throw new Exception("No configuration file found.", e);
        }
    }

LoadConfigDocument is used to load the .config file and to return XmlDocument Object.

We use it in the main core method ChangeValueByKey, where we first select the root node. Under his children, we find a single node which has the combination of our NodeForEdit and the specified key. Finally, the method changes the value of the found node.

If your goal is to modify and refresh the app.config, you need to call explicitly a code which reloads your configuration.

C#
public static void RefreshAppSettings()
{
   ConfigurationManager.RefreshSection("appSettings");
}

Find below two full examples how to use the ConfigModificator. The first code modifies and reloads the app.config. The second one shows how to change a custom XML configuration named “Cars.xml”.

C#
string appConfigFilePath = string.Concat(Assembly.GetExecutingAssembly().Location, ".config");
            ConfigModificatorSettings appConfigWriterSettings = 
                new ConfigModificatorSettings
                ("//appSettings", "//add[@key='{0}']", appConfigFilePath);
          
            string value = ConfigurationManager.AppSettings["testKey1"];
            System.Console.WriteLine("Value before modification: {0}", value);

            ConfigModificator.ChangeValueByKey(
                                                key: "testKey1", 
                                                value: "ChangedValueByModificator", 
                                                attributeForChange: "value", 
                                                configWriterSettings: appConfigWriterSettings);

            ConfigModificator.RefreshAppSettings();
            value = ConfigurationManager.AppSettings["testKey1"];
            System.Console.WriteLine("Value after modification: {0}", value);

            //Example how to change Custom XML configuration
            string carsConfigFilePath = "Cars.xml";
            ConfigModificatorSettings carsConfigWriterSettings = 
                new ConfigModificatorSettings
                ("//cars", "//car[@name='{0}']", carsConfigFilePath);

            ConfigModificator.ChangeValueByKey(
                                               key: "BMW",
                                               value: "Mazda",
                                               attributeForChange: "name",
                                               configWriterSettings: carsConfigWriterSettings);

Cars.xml

XML
<?xml version="1.0" encoding="utf-8" ?>
<testsConfiguration>
  <cars>
    <car name="Audi" price="10000" color="Red"/>
    <car name="BMW" price="20000" color="White"/>
  </cars>  
</testsConfiguration>

 

So Far in the C# Series

1. Implement Copy Paste C# Code
2. MSBuild TCP IP Logger C# Code
3. Windows Registry Read Write C# Code
4. Change .config File at Runtime C# Code
5. Generic Properties Validator C# Code
6. Reduced AutoMapper- Auto-Map Objects 180% Faster
7. 7 New Cool Features in C# 6.0
8. Types Of Code Coverage- Examples In C#
9. MSTest Rerun Failed Tests Through MSTest.exe Wrapper Application
10. Hints For Arranging Usings in Visual Studio Efficiently
11. 19 Must-Know Visual Studio Keyboard Shortcuts – Part 1
12. 19 Must-Know Visual Studio Keyboard Shortcuts – Part 2
13. Specify Assembly References Based On Build Configuration in Visual Studio
14. Top 15 Underutilized Features of .NET
15. Top 15 Underutilized Features of .NET Part 2
16. Neat Tricks for Effortlessly Format Currency in C#
17. Assert DateTime the Right Way MSTest NUnit C# Code
18. Which Works Faster- Null Coalescing Operator or GetValueOrDefault or Conditional Operator
19. Specification-based Test Design Techniques for Enhancing Unit Tests
20. Get Property Names Using Lambda Expressions in C#
21. Top 9 Windows Event Log Tips Using C#

 

If you enjoy my publications, feel free to SUBSCRIBE
Also, hit these share buttons. Thank you!

Source Code

 

The post- Change .config File at Runtime C# VB.NET Code appeared first on Automate The Planet.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO Automate The Planet
Bulgaria Bulgaria
CTO and Co-founder of Automate The Planet Ltd, inventor of BELLATRIX Test Automation Framework, author of "Design Patterns for High-Quality Automated Tests: High-Quality Test Attributes and Best Practices" in C# and Java. Nowadays, he leads a team of passionate engineers helping companies succeed with their test automation. Additionally, he consults companies and leads automated testing trainings, writes books, and gives conference talks. You can find him on LinkedIn every day.

Comments and Discussions

 
QuestionThank you but.. Pin
Anıl Cansu Taner22-Feb-15 23:15
Anıl Cansu Taner22-Feb-15 23:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.