读取配置节的通用方法我正在尝试实现一种从配置文件中读取节的通用方法。配置文件可能包含“标准”部分或“自定义”部分,如下所示。我尝试的方法如下:privatestringReadAllSections(){StringBuilderconfigSettings=newStringBuilder();配置configFile=ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);foreach(configFile.Sections中的ConfigurationSection部分){configSettings.Append(section.SectionInformation.Name);configSettings.Append(Environment.NewLine);if(section.GetType()==typeof(DefaultSection)){NameValueCollectionsectionSettings=ConfigurationManager.GetSection(section.SectionInformation.Name)asNameValueCollection;if(sectionSettings!=null){foreach(sectionSettings中的字符串键){configSettings.Append(key);configSettings.Append(":");configSettings.Append(sectionSettings[key]);configSettings.Append(Environment.NewLine);}}}configSettings.Append(Environment.NewLine);}返回configSettings.ToString();}假设所有自定义部分都只有KEY-VALUE更正/建议欢迎。谢谢。由于配置文件是XML文件,您可以使用XPath查询来执行此任务:ConfigurationconfigFile=ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);XmlDocument文档=newXmlDocument();文档.Load(configFile.FilePath);foreach(XmlNodenodeindocument.SelectNodes("//add")){stringkey=node.SelectSingleNode("@key").Value;字符串值=node.SelectSingleNode("@value").Value;Console.WriteLine("{0}={1}",key,value);}如果需要获取所有的{key,value}对,需要定义XPath查询的三元组:1-主要用于选择结构相似的节点进行查询。2,3,用于从第一个查询检索到的节点中提取键和值节点的查询。在您的情况下,对所有节点进行通用查询就足够了,但很容易维护对不同自定义部分的支持。将您的配置读入XmlDocument,然后使用XPath查找您要查找的元素?就像是;XmlDocumentdoc=newXmlDocument();doc.Load(HttpContext.Current.Server.MapPath("~/web.config"));XmlNodeListlist=doc.SelectNodes("//configuration/appSettings");foreach(XmlNodenodeinlist[0].ChildNodes)...你可以读取自定义部分如下:varsectionInformation=configuration.GetSection("mysection").SectionInformation;varxml=sectionInformation.GetRawXml();vardoc=newXmlDocument();doc.LoadXml(xml);IConfigurationSectionHandler处理程序=(IConfigurationSectionHandler)Type.GetType(sectionInformation.Type).GetConstructor(newType[0]).Invoke(newobject[0]);varresult=handler.Create(null,null,doc.DocumentElement);当您将NameValueSectionHandler指定为部分的类型属性并调用Configuration.GetSection(string)时,您将收到一个DefaultSection实例作为返回类型。stringSectionInformation.SectionInformation.GetRawXml()是本例中获取数据的关键。我用一个工作方法回答了另一个类似的问题,使用System.Configuration可以参考所有细节和代码片段。NameValueSectionHandler可以使用该section类型回写应用网络收集,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
