我正在尝试以编程方式访问Windows应用程序app.config文件。特别是,我试图访问“system.net/mailSettings” 以下代码
Configuration config = ConfigurationManager.OpenExeConfiguration(configFileName);
MailSettingsSectionGroup settings =
(MailSettingsSectionGroup)config.GetSectionGroup(@"system.net/mailSettings");
Console.WriteLine(settings.Smtp.DeliveryMethod.ToString());
Console.WriteLine("host: " + settings.Smtp.Network.Host + "");
Console.WriteLine("port: " + settings.Smtp.Network.Port + "");
Console.WriteLine("Username: " + settings.Smtp.Network.UserName + "");
Console.WriteLine("Password: " + settings.Smtp.Network.Password + "");
Console.WriteLine("from: " + settings.Smtp.From + "");
未能给予主持人。它只获取端口号。其余的都是空的;
答案 0 :(得分:18)
这似乎对我有用:
MailSettingsSectionGroup mailSettings =
config.GetSectionGroup("system.net/mailSettings")
as MailSettingsSectionGroup;
if (mailSettings != null)
{
string smtpServer = mailSettings.Smtp.Network.Host;
}
这是我的app.config文件:
<configuration>
<system.net>
<mailSettings>
<smtp>
<network host="mail.mydomain.com" />
</smtp>
</mailSettings>
</system.net>
</configuration>
但是,如Nathan所述,您可以使用应用程序或计算机配置文件为所有SmtpClient对象指定默认主机,端口和凭据值。有关更多信息,请参阅MDSN上的<mailSettings> Element。
答案 1 :(得分:11)
不确定这是否有帮助,但是如果您尝试制作SmtpClient,那么如果您使用默认构造函数,它将自动使用配置文件中的值。
答案 2 :(得分:8)
我使用以下方法访问mailSettings:
var config = ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
var mailSettings = config.GetSectionGroup("system.net/mailSettings")
as MailSettingsSectionGroup;
答案 3 :(得分:0)
private void button1_Click(object sender, EventArgs e)
{
try
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var mailSettings = config.GetSectionGroup("system.net/mailSettings")
as MailSettingsSectionGroup;
MailMessage msg = new MailMessage();
msg.Subject = "Hi Raju";
msg.To.Add("raju@hasten.in");
msg.From = new MailAddress("hasten.c@hasten.in");
msg.Body = "Hello Raju here everything is fine.";
//MailSettingsSectionGroup msetting = null;
string mMailHost = mailSettings.Smtp.Network.Host;
SmtpClient mailClient = new SmtpClient(mMailHost);
mailClient.Send(msg);
MessageBox.Show("Mail Sent Succesfully...");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}