我试图以编程方式访问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 + "");
未能给予主持人.它只获取端口号.其余的都是空的;
这对我来说似乎没问题:
MailSettingsSectionGroup mailSettings = config.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup; if (mailSettings != null) { string smtpServer = mailSettings.Smtp.Network.Host; }
这是我的app.config文件:
但是,如Nathan所述,您可以使用应用程序或计算机配置文件为所有SmtpClient对象指定默认主机,端口和凭据值.有关更多信息,请参阅MDSN上的
不确定这是否有帮助,但如果您正在尝试创建SmtpClient,那么如果您使用默认构造函数,它将自动使用配置文件中的值.
我使用以下方法来访问mailSettings:
var config = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None); var mailSettings = config.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;