c# - 使用 C# 自定义配置

标签 c# c#-4.0 app-config custom-configuration

我有一个带有自定义配置的 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();    
    }    
}

当我运行它时,我得到一个空字符串,但我应该得到“AnotherFoo”。我做错了什么?

最佳答案

如下所示替换第一行,以便您从配置文件中读取它而不是实例化一个新的..

WsaConfig config = ConfigurationManager.GetSection("wsa") as WsaConfig;

关于c# - 使用 C# 自定义配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30375614/

相关文章:

c# - 如何在不知道区域的情况下通过标签从缓存中获取项目

.net-4.0 - Entity Framework POCO 对象

c# - 服务层和存储库性能问题

c# - 使用 ConfigurationManager 从 App.config 读取嵌套值

c# - 使用 log4net 作为类库?

c# - MVVM灯下的异步命令执行

c# - 在 Umbraco 中对用户隐藏内容选项卡

c# - 如何实现无限集合类?

c# - 优化的 JSON 序列化器/反序列化器作为扩展方法?

c# - 在 app.config 中使用 XML 包含或配置引用来包含其他配置文件的设置