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



当我尝试使用

检索.config文件中的节列表时
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

配置。Sections集合包含了一堆系统节,但没有一个节我有文件定义在configSections标签。

这篇博客文章应该能让你得到你想要的。但是为了确保答案仍然可用,我将把代码也放在这里。简而言之,确保您引用了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; }
  }
}

确保你阅读了博客文章——它会给你一个背景,这样你就可以把它融入到你的解决方案中。

最新更新