读取配置部分的通用方法部分、方法

2023-09-03 16:06:13 作者:〖萍踪メ侠影〗

想实现一个通用的方式从一个配置文件中读取节。该配置文件可能包含标准部分或自定义部分如下图所示。

Am trying to implement a generic way for reading sections from a config file. The config file may contain 'standard' sections or 'custom' sections as below.

<configuration> 
<configSections>
	<section name="NoteSettings" type="System.Configuration.NameValueSectionHandler"/>
</configSections>	
<appSettings>
	<add key="AutoStart" value="true"/>
	<add key="Font" value="Verdana"/>
</appSettings>	
<NoteSettings>
	<add key="Height" value="100"/>
	<add key="Width" value="200"/>
</NoteSettings>

这是我试过的方法如下:

The method that I tried is as follows :

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

假设所有自定义栏目将只有键值的

是这样的实现可能吗?如果是,有没有比这个'清洁',更优雅的解决方案? 在上面的方法还写着看不见的部分,比如 mscorlib程序,System.Diagnostics程序的。这是可以避免的? 的 System.Data.DataSet中的返回而不能转换为NameValueCollection中的数据集。这又如何处理呢? Is such an implementation possible? And if yes, is there a 'cleaner' and more elegant solution than this one? The above method also reads 'invisible' sections like mscorlib, system.diagnostics. Is this avoidable? System.Data.Dataset returns a dataset which could not be cast to a NameValueCollection. How can this be handled?

更正/建议表示欢迎。

感谢。

推荐答案

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

Since configuration file is XML file, you can use XPath queries for this task:

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

如果你需要得到所有{键,值}对,那么你需要定义XPath查询的三胞胎: 1 - 选择具有相似结构的节点主查询。 2,3 - 查询提取键和值节点从第一个查询检索到的节点。你的情况,这足以对所有节点常用的查询,但可以很容易地保持不同的自定义的部分支持。

If you need to get all {key, value} pair then you need to define triplets of XPath queries: 1 - main query for selecting nodes with similar structure. 2, 3 - queries for extracting key and value nodes from nodes retrieved by first query. In your case it's enough to have common query for all nodes, but it's easy to maintain support for different custom sections.