我在我的 app.config 文件中使用自定义配置部分,当应用程序中发生错误时自动向某些管理员发送电子邮件,基于 Jan Remunda 的帖子:如何在 app.config 中创建自定义配置部分?
应用程序配置:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<configSections>
<section name="ErrorEmailer" type="EmailTester.ErrorEmailer" />
</configSections>
<ErrorEmailer>
<SmtpServer address="mail.smtphost.com" />
<FromAddress address="from@host.com" />
<ErrorRecipients>
<ErrorRecipient address="example@example.com" />
<ErrorRecipient address="example@example.com" />
</ErrorRecipients>
</ErrorEmailer>
</configuration>
我添加了这些配置元素:
public class ErrorRecipient : ConfigurationElement
{
[ConfigurationProperty("address", IsRequired = true)]
public string Address
{
get
{
return this["address"] as string;
}
}
}
public class SmtpServer : ConfigurationElement
{
[ConfigurationProperty("address", IsRequired = true)]
public string Address
{
get
{
return this["address"] as string;
}
}
}
public class FromAddress : ConfigurationElement
{
[ConfigurationProperty("address", IsRequired = true)]
public string Address
{
get
{
return this["address"] as string;
}
}
}
此配置元素集合:
public class ErrorRecipients : ConfigurationElementCollection
{
public ErrorRecipient this[int index]
{
get
{
return base.BaseGet(index) as ErrorRecipient;
}
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
public new ErrorRecipient this[string responseString]
{
get { return (ErrorRecipient)BaseGet(responseString); }
set
{
if (BaseGet(responseString) != null)
{
BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
}
BaseAdd(value);
}
}
protected override ConfigurationElement CreateNewElement()
{
return new ErrorRecipient();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((ErrorRecipient)element).Address;
}
}
而这个配置部分:
public class ErrorEmailer : ConfigurationSection
{
public static ErrorEmailer GetConfig()
{
return (ErrorEmailer)System.Configuration.ConfigurationManager.GetSection("ErrorEmailer") ?? new ErrorEmailer();
}
[ConfigurationProperty("ErrorRecipients")]
[ConfigurationCollection(typeof(ErrorRecipients), AddItemName = "ErrorRecipient")]
public ErrorRecipients ErrorRecipients
{
get
{
object o = this["ErrorRecipients"];
return o as ErrorRecipients;
}
}
[ConfigurationProperty("SmtpServer")]
public SmtpServer SmtpServer
{
get
{
object o = this["SmtpServer"];
return o as SmtpServer;
}
}
[ConfigurationProperty("FromAddress")]
public FromAddress FromAddress
{
get
{
object o = this["FromAddress"];
return o as FromAddress;
}
}
}
但是在运行程序并尝试运行此程序时出现“配置系统初始化失败”错误:
var config = ErrorEmailer.GetConfig();
Console.WriteLine(config.SmtpServer.Address);