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

Rou*_*nov 7 c# configurationmanager configsection

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

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Run Code Online (Sandbox Code Playgroud)

config.Sections集合包含一堆系统部分,但我没有在configSections标记中定义文件的部分.

Mik*_*oud 2

这是一篇博客文章,应该可以满足您的需求。但为了确保答案保持可用,我也将把代码放在这里。简而言之,确保您引用该System.Configuration程序集,然后利用该类ConfigurationManager来获取您想要的非常具体的部分。

\n\n
using System;\nusing System.Configuration;\n\npublic class BlogSettings : ConfigurationSection\n{\n  private static BlogSettings settings \n    = ConfigurationManager.GetSection("BlogSettings") as BlogSettings;\n\n  public static BlogSettings Settings\n  {\n    get\n    {\n      return settings;\n    }\n  }\n\n  [ConfigurationProperty("frontPagePostCount"\n    , DefaultValue = 20\n    , IsRequired = false)]\n  [IntegerValidator(MinValue = 1\n    , MaxValue = 100)]\n  public int FrontPagePostCount\n  {\n      get { return (int)this["frontPagePostCount"]; }\n        set { this["frontPagePostCount"] = value; }\n  }\n\n\n  [ConfigurationProperty("title"\n    , IsRequired=true)]\n  [StringValidator(InvalidCharacters = "  ~!@#$%^&*()[]{}/;\xe2\x80\x99\\"|\\\\"\n    , MinLength=1\n    , MaxLength=256)]\n  public string Title\n  {\n    get { return (string)this["title"]; }\n    set { this["title"] = value; }\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

请务必阅读博客文章 - 它将为您提供背景知识,以便您可以将其融入您的解决方案中。

\n