views:

4197

answers:

3

I am trying to programatically access 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 no. Rest are null;

+4  A: 

Not sure if this helps, but if you are trying to make a SmtpClient, that will automatically use the values in your config file if you use the default constructor.

Nathan Totten
+1 Use the default constructor on SmtpClient and it will do all this for you.
Richard Szalay
its not the same program config file i am tryin to read ... A different program is reading the config info...
+4  A: 

This seems to work ok for me:

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

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

Here's my app.config file:

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

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.

cxfx
+1  A: 

I used the following to access the mailSettings:

System.Configuration config = ConfigurationManager.OpenExeConfiguration(
    ConfigurationUserLevel.None);

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