【发布时间】:2010-10-18 13:37:49
【问题描述】:
早期,我在控制台应用程序中定义了自定义部分,它工作正常。但现在我想将一些功能移到库中。但是,不幸的是,我不能。因为现在我的自定义部分被定义为空。
简单的控制台应用程序包括以下代码:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
NotificationsConfigurationSection section
= NotificationsConfigurationSection.GetSection();
string emailAddress = section.EmailAddress;
Console.WriteLine(emailAddress);
Console.Read();
}
}
}
位于单独库中的具有自定义配置的文件包括下一个代码:
namespace ClassLibrary1
{
public class NotificationsConfigurationSection : ConfigurationSection
{
private const string configPath = "cSharpConsultant/notifications";
public static NotificationsConfigurationSection GetSection()
{
return (NotificationsConfigurationSection)
ConfigurationManager.GetSection(configPath);
}
/*This regular expression only accepts a valid email address. */
[RegexStringValidator(@"[\w._%+-]+@[\w.-]+\.\w{2,4}")]
/*Here, we register our configuration property with an attribute.
Note that the default value is required if we use
the property validation attributes, which will unfortunately
attempt to validate the initial blank value if a default isn't found*/
[ConfigurationProperty("emailAddress", DefaultValue = "Address@Domain.com")]
public string EmailAddress
{
get { return (string)this["emailAddress"]; }
set { this["emailAddress"] = value; }
}
}
}
在库的 app.config 中,我包含下一个节点:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="cSharpConsultant">
<section name="notifications"
type="ClassLibrary1.NotificationsConfigurationSection,
ClassLibrary1"/>
</sectionGroup>
</configSections>
<cSharpConsultant>
<notifications emailAddress="NotifiedPerson@Domain.com"/>
</cSharpConsultant>
</configuration>
有人可以帮帮我吗?
【问题讨论】:
标签: c# configuration