我有一个带自定义配置的App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="wsa" type="WSASRT.SRT.WSA.WsaConfig" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<wsa>
<src E="Foo@bar.com" CN="AnotherFoo" OU="AnotherBar" />
<!-- More elements -->
</wsa>
</configuration>
以下映射类
namespace WSASRT.SRT.WSA
{
class WsaConfig : ConfigurationSection
{
[ConfigurationProperty("src")]
public SrcElement Src { get { return (SrcElement)this["src"]; } }
}
public class SrcElement : ConfigurationElement
{
[ConfigurationProperty("E")]
public string E { get { return (String)this["E"]; } }
[ConfigurationProperty("CN")]
public string CN { get { return (String)this["CN"]; } }
}
}
我的Program.cs看起来像:
class Program
{
static void Main(string[] args)
{
WsaConfig config = new WsaConfig();
Console.WriteLine(config.Src.CN);
Console.ReadLine();
}
}
当我运行它时,我得到一个空字符串,但我应该得到&#34; AnotherFoo&#34;。我做错了什么?
答案 0 :(得分:1)
如下所示替换第一行,以便从配置文件&amp;中读取它。没有实例化新的..
WsaConfig config = ConfigurationManager.GetSection("wsa") as WsaConfig;