如何以编程方式从web.config中检索smtp服务器详细信息

JL.*_*JL. 7 c# web-config

我在web.config中存储了以下SMTP详细信息

<system.net>
    <mailSettings>
      <smtp from="isds@ixtent.com">
        <network host="mail.domain.com" port="25" userName="username" password="password" defaultCredentials="true"/>
      </smtp>
    </mailSettings>
  </system.net>
Run Code Online (Sandbox Code Playgroud)

如何从ac#class中检索这些值.

Dar*_*rov 18

Configuration configurationFile = WebConfigurationManager
    .OpenWebConfiguration("~/web.config");
MailSettingsSectionGroup mailSettings = configurationFile
    .GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
if (mailSettings != null)
{
    int port = mailSettings.Smtp.Network.Port;
    string host = mailSettings.Smtp.Network.Host;
    string password = mailSettings.Smtp.Network.Password;
    string username = mailSettings.Smtp.Network.UserName;
}
Run Code Online (Sandbox Code Playgroud)

  • 一点点:不会"〜/ web.config"更可靠吗? (2认同)