当我尝试使用检索 .config 文件中的部分列表时
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.Sections 集合包含一堆系统部分,但我在 configSections 标记中定义的文件中没有任何部分。
这里有一个博客文章 http://haacked.com/archive/2007/03/11/custom-configuration-sections-in-3-easy-steps.aspx那应该可以得到你想要的。但为了确保答案保持可用,我也将把代码放在这里。简而言之,请确保您引用的是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; }
}
}
请务必阅读博客文章 - 它将为您提供背景知识,以便您可以将其融入您的解决方案中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)