Change .config File at Runtime C# Code

.NET
Share
Change .config File at Runtime C# Code

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:

<?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:

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 that 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 that 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);
//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 version=1.0 encoding=utf-8 ?>
<testsConfiguration>
<cars>
<car name=Audi price=10000 color=Red/>
<car name=BMW price=20000 color=White/>
</cars>
</testsConfiguration>

.NET Series

YouTube Playlists API C# Code
18/07/2014 / By Anton Angelov
MSBuild TCP IP Logger C# Code
16/03/2014 / By Anton Angelov
7 New Cool Features in C# 6.0
26/10/2014 / By Anton Angelov
Top 15 Underutilized Features of .NET
23/08/2015 / By Anton Angelov