2

I was using a certain method for parsing my app.config file. Then I was told that using ConfigurationManager is better and simpler. But the thing is I don't know how to do it with ConfigurationManager.

My original code looked like this:

   XmlNode xmlProvidersNode;
    XmlNodeList xmlProvidersList;
    XmlNodeList xmlTaskFactoriesList;

    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load("app.config");
    xmlProvidersNode = xmlDoc.DocumentElement.SelectSingleNode("TaskProviders");
    xmlProvidersList = xmlProvidersNode.SelectNodes("TaskProvider");

    foreach (XmlNode xmlProviderElement in xmlProvidersList)
    {
        if (xmlProviderElement.Attributes.GetNamedItem("Name").Value.Equals(_taskProvider))
        {
            xmlTaskFactoriesList = xmlProviderElement.SelectNodes("TaskTypeFactory");
            foreach (XmlNode xmlTaskFactoryElement in xmlTaskFactoriesList)
            {
                if (xmlTaskFactoryElement.Attributes.GetNamedItem("TaskType").Value.Equals(_taskType))
                {
                    taskTypeFactory = xmlTaskFactoryElement.Attributes.GetNamedItem("Class").Value;
                }
            }
        }
    }

What would be the equivalent using ConfigurationManager? (Because all I can see is how to get keys not nodes..)

Thanks

2 Answers 2

4

Create a class that inherits ConfigurationSection called, say, MyConfigSection. Then you can use the ConfigurationManager.GetSection method to get an instance of your MyConfigSection class. The ConfigurationManager will do all the parsing, so you will have a strongly typed object to work with. Here is an excellent example to follow.

Sign up to request clarification or add additional context in comments.

2 Comments

And you said it was simpler! Thank you for the link, I'll read it.
@Amokrane, it may not be simpler the first time you use it, but I generally find that is it a good practice to work with the framework and not invent your own half-baked solutions to problems that have already been solved by people in Redmond WA ;-)
2

If you are concerned about the custom sections create your own class using Configuration section class. Here is an example about using it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.