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.
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:
="1.0" ="utf-8"
<configuration>
<appSettings>
<add key="testKey " value="1" />
<add key="testKey1" value="myTestValue" />
</appSettings>
</configuration>
We use the following settings object:
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.
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.
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”.
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);
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
="1.0" ="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.