HOW TO: Accessing Config File Mail Settings Programmatically
The .NET Framework 2.0 provides APIs for accessing settings in a configuration file. Here's how you access the mail settings of a config file programmatically:
C#
using System.Configuration; using System.Web.Configuration; using System.Net.Configuration; Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration("PathToConfigFile"); 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; }VB.NET
Imports System.Configuration Imports System.Web.Configuration Imports System.Net.Configuration Dim configurationFile As Configuration = WebConfigurationManager.OpenWebConfiguration("PathToConfigFile") Dim mailSettings As MailSettingsSectionGroup = configurationFile.GetSectionGroup("system.net/mailSettings") If Not mailSettings Is Nothing Then Dim port As Integer = mailSettings.Smtp.Network.Port Dim host As String = mailSettings.Smtp.Network.Host Dim password As String = mailSettings.Smtp.Network.Password Dim username As String = mailSettings.Smtp.Network.UserName End If