C# .NET - Cannot read mail settings form web.config file

Asked By abinav shankar on 30-Jan-12 11:51 PM
I have used the following code to read the config file and i get only the default port number and nothing else
 pl check the code and tell me what should be done

Web.config file:

    <smtp from="abinav@ymail.com">
    <network host="smtp.bizmail.yahoo.com" port="25" userName="abinav@ymail.com" password="Mypassword" defaultCredentials="true" />

Used the following code to convert the physical path to virtual path

public static Configuration OpenConfigFile(string configPath)
    var configFile = new FileInfo(configPath);
    var vdm = new VirtualDirectoryMapping(configFile.DirectoryName, true, configFile.Name);
    var wcfm = new WebConfigurationFileMap(); wcfm.VirtualDirectories.Add("/", vdm);
    return WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");

Used the above method to read the config file

string strConfigPath = Server.MapPath("~/LeaveManagementSystem_30_01_2012/web.config");
     //strConfigPath = @"~/web.config";// HttpContext.Current.Request.ApplicationPath + "/" + "web.config";
     Configuration config = OpenConfigFile(strConfigPath) as Configuration;
     MailSettingsSectionGroup mailSettings = config.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;

but I can read only the default port setting not the one mentioned in the web.config file

smr replied to abinav shankar on 30-Jan-12 11:54 PM

Just specifying it should be declare like that:

Dim config As System.Configuration.Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(------your configPath as string -------)

smr replied to abinav shankar on 30-Jan-12 11:54 PM

try this

System.Net.Configuration.SmtpSection smtp = new System.Net.Configuration.SmtpSection();
string from = smtp.From;
System.Net.Configuration.SmtpNetworkElement nt = new System.Net.Configuration.SmtpNetworkElement();
string host = nt.Host;
Jitendra Faye replied to abinav shankar on 30-Jan-12 11:57 PM
Use this code-

You can use:

public string GetPickupDirectory()
    var config = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection;


This code will give you SMTP setting from current web.config file.

abinav shankar replied to Jitendra Faye on 31-Jan-12 12:20 AM
Thanks i got it now
Jitendra Faye replied to abinav shankar on 31-Jan-12 12:28 AM