我正在使用某种方法来解析我的 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/