从代码中获取App.config设置

时间:2016-10-22 23:03:40

标签: c# app-config

我正在尝试通过我的代码获取app.config的属性,但是我一直收到一个无法识别的元素异常。我的代码如下:

// Program.cs中

static void Main(string[] args)
{
TraderConfig _traderConfig = (TraderConfig)ConfigurationManager.GetSection("connections");
}

// App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="connections" type="Trader.TraderConfig,  Trader" />
</configSections>
<connections>
<connection name="F">
</connection>
</connections>
</configuration>

// TraderConfig.cs 这是我认为导致错误的部分。

namespace Trader
{
public class TraderConfig : ConfigurationSection
{
private static TraderConfig _traderConfig = (TraderConfig)ConfigurationManager.GetSection("connection");
public static TraderConfig Settings { get { return _traderConfig; } }

[ConfigurationProperty("name")]
public string Name { get { return (string)base["name"]; } }

[ConfigurationProperty("connections")]
public ConnectionElementCollection Connections { get { return (ConnectionElementCollection)base["connections"]; } }

}

public class ConnectionElement : ConfigurationElement
{
 [ConfigurationProperty("name")]
 public string Name { get { return (string)base["name"]; } }

 [ConfigurationProperty("connections")]
 public ConnectionElementCollection Connections { get { return (ConnectionElementCollection)base["connections"]; } }
}

[ConfigurationCollection(typeof(ConnectionElement), AddItemName = "connection", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class ConnectionElementCollection : ConfigurationElementCollection
{
public ConfigurationElementCollectionType CollectionType
{ get { return ConfigurationElementCollectionType.BasicMap; } }

protected override string ElementName
{ get { return "connection"; } }

protected override ConfigurationElement CreateNewElement()
{ return new ConnectionElement(); }

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

public ConnectionElement this[int index]
 {
 get { return (ConnectionElement)base.BaseGet(index); }
 set
 {
 if (base.BaseGet(index) != null)
 {
 base.BaseRemoveAt(index);
 }
 base.BaseAdd(index, value);
 }
}

public ConnectionElement this[string name]
{ get { return (ConnectionElement)base.BaseGet(name); } }
}
}

0 个答案:

没有答案