在C#编程的app.config访问system.net设置 [英] Access system.net settings from app.config programmatically in C#

查看:233
本文介绍了在C#编程的app.config访问system.net设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图以编程方式访问Windows应用程序的app.config文件。特别是,我试图访问system.net/mailSettings
下面的代码

I am trying to programmatically access a Windows application app.config file. In particular, I am trying to access the "system.net/mailSettings" The following code

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 + "");



未能给予主机,从。它只是变得端口号。其余的都是空;

fails to give the host, from. it only gets the port number. The rest are null;

推荐答案

这似乎为我工作确定:

MailSettingsSectionGroup mailSettings =
    config.GetSectionGroup("system.net/mailSettings")
    as MailSettingsSectionGroup;

if (mailSettings != null)
{
    string smtpServer = mailSettings.Smtp.Network.Host;
}

下面就是我的app.config文件:

Here's my app.config file:

<configuration>
  <system.net>
    <mailSettings>
      <smtp>
        <network host="mail.mydomain.com" />
      </smtp>
    </mailSettings>
  </system.net>
</configuration>



然而,如弥敦道所述,您可以使用该应用程序或机器配置文件来指定默认主机,所有 SmtpClient 对象端口和凭据值。欲了解更多信息,请参见< mailSettings> 的元素上MDSN。

However, as stated by Nathan, you can use the application or machine configuration files to specify default host, port, and credentials values for all SmtpClient objects. For more information, see <mailSettings> Element on MDSN.

这篇关于在C#编程的app.config访问system.net设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆