Its possible to use the config file as XML and then use XPath to change values:
using (TransactionScope transactionScope = new TransactionScope())
{
XmlDocument configFile = new XmlDocument();
configFile.Load("PathToConfigFile");
XPathNavigator fileNavigator = configFile.CreateNavigator();
// User recursive function to get to the correct node and set the value
WriteValueToConfigFile(fileNavigator, pathToValue, newValue);
configFile.Save("PathToConfigFile");
// Commit transaction
transactionScope.Complete();
}
private void WriteValueToConfigFile(XPathNavigator fileNavigator, string remainingPath, string newValue)
{
string[] splittedXPath = remainingPath.Split(new[] { '/' }, 2);
if (splittedXPath.Length == 0 || String.IsNullOrEmpty(remainingPath))
{
throw new Exception("Path incorrect.");
}
string xPathPart = splittedXPath[0];
XPathNavigator nodeNavigator = fileNavigator.SelectSingleNode(xPathPart);
if (splittedXPath.Length > 1)
{
// Recursion
WriteValueToConfigFile(nodeNavigator, splittedXPath[1], newValue);
}
else
{
nodeNavigator.SetValue(newValue ?? String.Empty);
}
}
Possible path to Conf1:
"configuration/applicationSettings/ExternalConfigReceiver.Properties.Settings/setting[name=\"Conf1\"]/value"