读取配置节的通用方法

我试图实现从配置文件中读取节通用方法 。 配置文件可能包含“标准”部分或“自定义”部分,如下所示。

  

我尝试的方法如下:

  private string ReadAllSections() { StringBuilder configSettings = new StringBuilder(); Configuration configFile = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); foreach (ConfigurationSection section in configFile.Sections) { configSettings.Append(section.SectionInformation.Name); configSettings.Append(Environment.NewLine); if (section.GetType() == typeof(DefaultSection)) { NameValueCollection sectionSettings = ConfigurationManager.GetSection(section.SectionInformation.Name) as NameValueCollection; if (sectionSettings != null) { foreach (string key in sectionSettings) { configSettings.Append(key); configSettings.Append(" : "); configSettings.Append(sectionSettings[key]); configSettings.Append(Environment.NewLine); } } } configSettings.Append(Environment.NewLine); } return configSettings.ToString(); } 

假设所有自定义部分都只有KEY-VALUE

  • 这样的实现是否可行? 如果是的话,是否有比这更“干净”且更优雅的解决方案?
  • 上面的方法还会读取像mscorlib,system.diagnostics这样的“不可见”部分。 这是可以避免的吗?
  • System.Data.Dataset返回无法强制转换为NameValueCollection的数据集。 怎么办呢?

更正/建议欢迎。

谢谢。

由于配置文件是XML文件,因此您可以使用XPath查询执行此任务:

  Configuration configFile = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location); XmlDocument document = new XmlDocument(); document.Load(configFile.FilePath); foreach (XmlNode node in document.SelectNodes("//add")) { string key = node.SelectSingleNode("@key").Value; string value = node.SelectSingleNode("@value").Value; Console.WriteLine("{0} = {1}", key, value); } 

如果需要获取所有{key,value}对,则需要定义XPath查询的三元组:1 – 用于选择具有相似结构的节点的主查询。 2,3,用于从第一次查询检索的节点中提取键和值节点的查询。 在您的情况下,它足以对所有节点进行通用查询,但很容易维护对不同自定义节的支持。

将您的配置读入XmlDocument然后使用XPath查找您要查找的元素?

就像是;

 XmlDocument doc = new XmlDocument(); doc.Load(HttpContext.Current.Server.MapPath("~/web.config")); XmlNodeList list = doc.SelectNodes("//configuration/appSettings"); foreach (XmlNode node in list[0].ChildNodes) 

您可以按如下方式阅读自定义部分:

 var sectionInformation = configuration.GetSection("mysection").SectionInformation; var xml = sectionInformation.GetRawXml(); var doc = new XmlDocument(); doc.LoadXml(xml); IConfigurationSectionHandler handler = (IConfigurationSectionHandler)Type.GetType(sectionInformation.Type).GetConstructor(new Type[0]).Invoke(new object[0]); var result = handler.Create(null, null, doc.DocumentElement); 

当您将NameValueSectionHandler指定为节的type属性并调用Configuration.GetSection(string) ,您将收到一个DefaultSection实例作为返回类型。

string SectionInformation.SectionInformation.GetRawXml()是这种情况下进入数据的关键。

我用一个有效的方法回答了另一个类似的问题,使用System.Configuration可以引用它来获取所有细节和代码片段。 NameValueSectionHandler可以使用此节类型写回应用程序