如何从App.config中读取自定义配置?

10

如何从App.config读取自定义配置?

<root name="myRoot" type="rootType">
    <element name="myName" type="myType" />
    <element name="hisName" type="hisType" />
    <element name="yourName" type="yourType" />
  </root>

不要这样做:

<root name="myRoot" type="rootType">
  <elements>
    <element name="myName" type="myType" />
    <element name="hisName" type="hisType" />
    <element name="yourName" type="yourType" />
  </elements>
  </root>

1
如果这些答案没有完全帮助到您,请提供更多信息,以便我们进一步协助。 - Haukman
4个回答

31

要使您的集合元素直接位于父元素中(而不是子集合元素),您需要重新定义ConfigurationProperty。例如,假设我有一个如下的集合元素:

public class TestConfigurationElement : ConfigurationElement
{
    [ConfigurationProperty("name", IsKey = true, IsRequired = true)]
    public string Name
    {
        get { return (string)this["name"]; }
    }
}

并且一个类似于:

[ConfigurationCollection(typeof(TestConfigurationElement), AddItemName = "test")]
public class TestConfigurationElementCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new TestConfigurationElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((TestConfigurationElement)element).Name;
    }
}

我需要定义父级部分/元素为:

public class TestConfigurationSection : ConfigurationSection
{
    [ConfigurationProperty("", IsDefaultCollection = true)]
    public TestConfigurationElementCollection Tests
    {
        get { return (TestConfigurationElementCollection)this[""]; }
    }
}

注意[ConfigurationProperty("", IsDefaultCollection = true)]属性。将其命名为空并将其设置为默认集合,可以让我像这样定义我的配置:

<testConfig>
  <test name="One" />
  <test name="Two" />
</testConfig>

不要:

<testConfig>
  <tests>
    <test name="One" />
    <test name="Two" />
  </tests>
</testConfig>

7

4

由于这不是标准的配置文件格式,您需要将配置文件作为XML文档打开,然后提取部分(例如使用XPath)。请使用以下方式打开文档:

// Load the app.config file
XmlDocument xml = new XmlDocument();
xml.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

0

我认为你可以使用

            XmlDocument appSettingsDoc = new XmlDocument();
            appSettingsDoc.Load(Assembly.GetExecutingAssembly().Location + ".config");
            XmlNode node = appSettingsDoc.SelectSingleNode("//appSettings");

            XmlElement element= (XmlElement)node.SelectSingleNode(string.Format("//add[@name='{0}']", "myname"));
            string typeValue = element.GetAttribute("type");

希望这能解决你的问题。编程愉快。 :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接