如何使用C#检索.config文件中自定义配置部分的列表?

7
当我尝试使用以下代码检索.config文件中的部分列表时:

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

config.Sections集合包含一些系统部分,但其中没有我在configSections标记中定义的任何部分。

1个回答

2
这是一篇博客文章,应该可以帮助你找到想要的内容。为了确保答案始终可用,我将在此处放置代码。简而言之,请确保引用了System.Configuration程序集,然后利用ConfigurationManager类来获取您想要的非常具体的部分。
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; }
  }
}

确保你阅读了博客文章 - 这将为你提供背景,以便你可以将其融入你的解决方案中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接