我怎样才能检索使用C#的config文件自定义配置节的列表? [英] How can I retrieve list of custom configuration sections in the .config file using C#?

查看:352
本文介绍了我怎样才能检索使用C#的config文件自定义配置节的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用检索的config文件部分的列表

When I try to retrieve the list of sections in the .config file using

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);



config.Sections集合包含了一堆系统部分,但没有一个部分我在定义文件在configSections标签。

the config.Sections collection contains a bunch of system section but none of the sections I have file defined in the configSections tag.

推荐答案

下面是一个的博客文章,应该得到你想要的东西。但是,为了确保答案可以保持我要去的地方砸代码在这里了。总之,确保你引用 System.Configuration 程序集,然后利用 ConfigurationManager中类来获得在你要非常具体的部分。

Here is a blog article that should get you what you want. But to ensure that the answer stays available I'm going to drop the code in place here too. In short, make sure you're referencing the System.Configuration assembly and then leverage the ConfigurationManager class to get at the very specific sections you want.

using System;
using System.Configuration;

public class BlogSettings : ConfigurationSection
{
  private static BlogSettings settings 
    = ConfigurationManager.GetSection("BlogSettings") as BlogSettings;

  public static BlogSettings Settings
  {
    get
    {
      return settings;
    }
  }

  [ConfigurationProperty("frontPagePostCount"
    , DefaultValue = 20
    , IsRequired = false)]
  [IntegerValidator(MinValue = 1
    , MaxValue = 100)]
  public int FrontPagePostCount
  {
      get { return (int)this["frontPagePostCount"]; }
        set { this["frontPagePostCount"] = value; }
  }


  [ConfigurationProperty("title"
    , IsRequired=true)]
  [StringValidator(InvalidCharacters = "  ~!@#$%^&*()[]{}/;’\"|\\"
    , MinLength=1
    , MaxLength=256)]
  public string Title
  {
    get { return (string)this["title"]; }
    set { this["title"] = value; }
  }
}

请务必阅读博客文章 - 它会给你的背景,使你能适应它变成您的解决方案

Make sure you read the blog article - it will give you the background so that you can fit it into your solution.

这篇关于我怎样才能检索使用C#的config文件自定义配置节的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆