C#从外部dll中读取web.config中的<system.net> <mailsettings> </mailsettings> </system.net>

时间:2010-07-16 14:29:43

标签: c# dll smtp web-config

我的网络应用程序调用外部DLL。在dll中我想访问system.net/mailSettings/smtp部分中的specifiedPickupDirectory pickupDirectoryLocation值。如何从dll代码中获取它?

这样的东西
System.Configuration.ConfigurationSettings.GetConfig("configuration/system.net/mailSettings/smtp/specifiedPickupDirectory/pickupDirectoryLocation")

但这不起作用

3 个答案:

答案 0 :(得分:17)

您可以使用:

public string GetPickupDirectory()
{
    var config = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection;

    return (config != null) ? config.SpecifiedPickupDirectory : null;
}

答案 1 :(得分:6)

我想你可以简单地使用PickupDirectoryLocation属性。

// if .NET 4.0 don't forget that SmtpClient is IDisposable
SmtpClient client = new SmtpClient();
string pickupLocation = client.PickupDirectoryLocation;

通过这种方式,您不会在代码中使用魔术字符串,如果在框架的未来版本中此属性更改配置文件中的名称或位置,则不必担心。

答案 2 :(得分:0)

使用它:

using System.Configuration;
using System.Web.Configuration;
using System.Net.Configuration;

然后:

Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
MailSettingsSectionGroup settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");

然后你就可以访问

//settings.Smtp.SpecifiedPickupDirectory;

当然,这也应该在System.Net.Mail.SmtpClient.PickupDirectoryLocation属性中找到