How to parse app.config using ConfigurationManager?

两盒软妹~` 提交于 2020-01-02 09:36:05

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/2804390/how-to-parse-app-config-using-configurationmanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!