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

4 に答える 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>
于 2011-06-11T08:32:40.253 に答える
7

System.Configuration.GetSection() メソッドを使用して、カスタム構成セクションを読み取ることができます。

GetSection() の詳細については、http://msdn.microsoft.com/en-us/library/system.configuration.configuration.getsection.aspx を参照してください。

于 2011-06-02T18:24:59.147 に答える
4

これは標準の構成ファイル形式ではないため、構成ファイルを XML ドキュメントとして開き、セクションを (たとえば XPath を使用して) 取り出す必要があります。これでドキュメントを開きます:

// Load the app.config file
XmlDocument xml = new XmlDocument();
xml.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
于 2011-06-11T07:35:10.947 に答える
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");

これで問題が解決することを願っています。ハッピーコーディング。:)

于 2011-06-15T02:26:07.930 に答える