0

Since a few days i'm working with ConfigurationSection. I was dealing with multiple config files with different extensions. Making long story short, We've decided to store some configs as Xpaths, and the question is: what is the best way to update ConfigurationSection while having new values as Xpaths?

This code is working:

//section is an instance of ConfigurationSection, newConfig is an object with Xpath and value
var rawSectionXml = section.SectionInformation.GetRawXml(); 
XDocument sectionAsXml = null;
using (StringReader sr = new StringReader(rawSectionXml))
{
    using (XmlReader xmlReader = XmlReader.Create(sr))
    {
        sectionAsXml = XDocument.Load(xmlReader);
    }
}

var sectionAsXmlAttribute = ((IEnumerable<object>)sectionAsXml.XPathEvaluate(newConfig.XPath)).OfType<XAttribute>().FirstOrDefault();
sectionAsXmlAttribute.Value = newConfig.Value;
section.SectionInformation.SetRawXml(sectionAsXml.ToString());

Is there any simpler way of doing this? Is it possible to do the same without converting ConfigurationSection to XDocument?

burgund
  • 357
  • 1
  • 5
  • 12
  • 1
    Can you elaborate what it means to "store some configs as Xpaths"? What is the use case for this? I mean where is `newConfig` coming from and why do you need to update the configuration at runtime? It's a little difficult to understand the premise of the question which makes suggestions for improvement difficult. – Xerillio Oct 24 '22 at 17:44
  • Storing configs as Xpaths is a solution (probably just one of plenty) for storing xml sections in yaml files. In this particular case we're using key as xpath for given value. `newConfig` is coming from yaml file. There is a possibility to add configuration yaml files as args when starting app, then app is doing it's own magic on initialization (deciding which value should be used and from which file). – burgund Oct 26 '22 at 12:36
  • Hmm, it might just be my ignorance, but you explain it as if "storing xml sections in yaml files" is a normal thing to do - not to me. To give any valuable input, from me at least, I think you need to reverse a bit and explain what the underlying problem you're trying to solve here is. Why would you need to store the same configuration both in XML (web.config?) and YAML? Is this some kind of deployment/environment override setup? If it's just this code snippet you want feedback on, then: "if it works it works" - it doesn't look so complicated that I would bother improving if it does its job. – Xerillio Oct 26 '22 at 19:18

0 Answers0