c# - 如何使用ConfigurationManager解析app.config?

标签 c# app-config configurationmanager

我正在使用某种方法来解析我的 app.config 文件。然后我被告知使用 ConfigurationManager 更好、更简单。但问题是我不知道如何使用 ConfigurationManager 来做到这一点。

我的原始代码如下所示:

   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;
                }
            }
        }
    }

使用 ConfigurationManager 的等效效果是什么? (因为我所能看到的只是如何获取键而不是节点..)

谢谢

最佳答案

创建一个继承 ConfigurationSection 的类,例如,MyConfigSection。然后,您可以使用 ConfigurationManager.GetSection 方法来获取 MyConfigSection 类的实例。 ConfigurationManager 将完成所有解析,因此您将拥有一个可以使用的强类型对象。 Here is an excellent example to follow.

关于c# - 如何使用ConfigurationManager解析app.config?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2804390/

相关文章:

c# - 计算玩家输赢百分比

c# - 不懂 IEnumerable<T>

c# - HttpContent:已添加具有相同键的项目

c# - 只有一位小数的字符串格式?

c# - 在运行时修改 app.config <system.diagnostics> 部分

c# - ConfigurationManager 的命名空间在哪里?

c# - ConfigurationManager.OpenExeConfiguration - 加载错误的文件?

c# - 在运行时更改其他项目的 app.config 值

c# - 配置系统初始化失败

c# - 覆盖预构建和使用设置中的 App.Config