views:

57

answers:

2

Hi,

I want to add an ability to an application that I'm developing for accessing configuration. The application will search by default in the app.config file for a section that I give it. If it was not found in the app.config, it will look for it in the DB, in a specific table that has the following columns:

SectionType, SectionName, SectionData

The SectionData column is a text column, that contains the data of the section in XML format (exactly like it should be in the app.config file) I can take the SectionData content, but I can't load it into the custom ConfigurationSection, like I would have done if it was in the app.config file:

var mySectionObj = ConfigurationManager.GetSection("myCustomSection");

To simplify, my question is actually how can I get the custom ConfigurationSection object from a XML string instead of a configuration file?

A: 

You could load the string into an XDocument object and read it from there.

Kjartan Þór Kjartansson
A: 

I don't think that's possible at all - with the ConfigurationManager class from .NET, it is as far as I know not even possible to open whatever file you want - you are restricted to the app.config file. Reading configuration data from another source than a file? No can do.

You can either analyse the XML-String yourself (with "XmlDocument.LoadXml(string)") or you modify the app.config file and read it again.

The question would be: Why wouldn't there be the CustomSection in the config file? Should this be considered an error (then updating the config file would be best, I think). Or is it intended, that some config files don't have the CustomSection?

If the settings may be in the XML-File, adding the setting to the file would be like this:

XmlDocument appconfig = new XmlDocument();

appconfig.Load("[config_filename]");
XmlNode root = appconfig.DocumentElement;

XmlDocument mysection = new XmlDocument();
mysection.LoadXml([SectionData]);
XmlNode customSection = mysection.DocumentElement;

XmlNode tempNode = appconfig.ImportNode(customSection, true);
root.AppendChild(tempNode);

appconfig.Save("[config_filename]");

...

var mySectionObj = ConfigurationManager.GetSection("myCustomSection");

if this is not desirable, I see two possibilities: First: Do it nevertheless: Change the .config file, read it, and then change it back. (or copy the file, change the original, read it, delete it, rename the copy back to the original name). This way is not nice, it's somehow impure, in my opinion, but it has some great advantages: It works and it is easy to maintain.

Second: Load your XML string into a XmlDocument: XmlDocument.LoadXml(xmlstring) Then analyse the xmldocument, with "doc.ChildNodes" or "doc.SelectNodes(xpath)" or "doc.SelectSingleNode(xpath)". This will be much more work, especially since you will have to maintain to routines to get the configuration settings into your project, so I would not recommend this method. Strongly not recommend.

Alex