读取配置节的通用方法

时间:2009-01-15 15:36:06

标签: c# .net version-control

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

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

我尝试的方法如下:

    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的数据集。怎么办呢?

欢迎更正/建议。

感谢。

4 个答案:

答案 0 :(得分:9)

由于配置文件是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-用于从第一查询检索的节点中提取键和值节点的查询。在您的情况下,它足以对所有节点进行通用查询,但很容易维护对不同自定义节的支持。

答案 1 :(得分:2)

将您的配置读入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)

...

答案 2 :(得分:2)

您可以按如下方式阅读自定义栏目:

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

答案 3 :(得分:1)

如果您已将NameValueSectionHandler指定为某个部分的类型属性并调用Configuration.GetSection(string),则会收到一个DefaultSection实例作为返回类型。

在这种情况下,

string SectionInformation.SectionInformation.GetRawXml()是获取数据的关键。

我使用System.Configuration以有效的方式回答了另一个类似的问题,您可以参考该问题获取所有详细信息和代码段。 NameValueSectionHandler can i use this section type for writing back to the app

相关问题