C# 自定义配置文件

先来一段代码,创建了一个名为TestSection的节点

namespace  _51Take.Testing
{
    public class TestSection : ConfigurationSection
    {
        private static ConfigurationProperty s_property = new ConfigurationProperty(string.Empty, typeof(TestCollection), null,                ConfigurationPropertyOptions.IsDefaultCollection);
        [ConfigurationProperty("", Options = ConfigurationPropertyOptions.IsDefaultCollection)]
        public TestCollection TestCollections
        {
            get { return (TestCollection)base[s_property]; }
        }
    }
    [ConfigurationCollection(typeof(TestConfig))]
    public class TestCollection : ConfigurationElementCollection
    {
        public TestCollection() : base(StringComparer.OrdinalIgnoreCase) { }
        new public TestConfig this[string name]
        {
            get { return (TestConfig)base.BaseGet(name); }
            set { base[name] = value; }
        }
        protected override ConfigurationElement CreateNewElement()
        {
            return new TestConfig();
        }
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((TestConfig)element).Name;
        }
    }

 // 这里是节点里面的属性,随意添加
    public class TestConfig : ConfigurationElement
    {
        [ConfigurationProperty("Name", IsRequired = true)]
        public string Name
        {
            get { return this["Name"].ToString(); }
            set { this["Name"] = value; }
        }
        [ConfigurationProperty("Age", IsRequired = true)]
        public string Age
        {
            get { return this["Age"].ToString(); }
            set { this["Age"] = value; }
        }
    }

上面的代码其实百度上都差不多,但是最重要的没说

运行下去你会发现报错

解决这个问题你需要在配置文件添加这一段,name是节点名,type内容,逗号前是节点类的命名空间加上类名,逗号后是节点类所在类库的类库名

然后读

           var config = ConfigurationManager.GetSection("TestSection") as TestSection;
            TestConfig pt = config.TestCollections.Cast<TestConfig>().FirstOrDefault();

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值