2009-03-09 2 views
14

Windowsアプリケーションのapp.configファイルにプログラムでアクセスしようとしています。特に、私は 「system.net/mailSettings」にアクセスするには、次のコードをしようとしていますC言語でプログラムによってapp.configからsystem.net設定にアクセスする

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

から、ホストを与えることができません。ポート番号のみを取得します。残りはnullです。

+0

PLSのは質問である設定ファイルのセクションを投稿してください。 – abhilash

+0

smtp設定...私はsystem.net設定にアクセスしようとしています。 –

答えて

11

SmtpClientを作成しようとしている場合、デフォルトのコンストラクタを使用している場合は、この設定ファイルの値が自動的に使用されます。

+1

+1 SmtpClientのデフォルトのコンストラクタを使用すると、すべてこれを行います。 –

+0

それは同じプログラムの設定ファイルではありません...私は試してみています...別のプログラムが設定情報を読み込んでいます... –

18

これは私のために[OK]を動作するようです:

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

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

ここに私のapp.configファイルがあります:

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

しかし、ネイサンで述べたように、あなたがアプリケーションやマシンの構成ファイルを使用することができますすべてのSmtpClientオブジェクトのデフォルトのホスト、ポート、および資格情報の値を指定します。詳細については、MDSNの<mailSettings> Elementを参照してください。

+0

私は同じコードを使用していますが、常にmailSettingsはnullです – kbvishnu

8

私はmailSettingsアクセスするには、次を使用:

var config = ConfigurationManager.OpenExeConfiguration(
    ConfigurationUserLevel.None); 

var mailSettings = config.GetSectionGroup("system.net/mailSettings") 
    as MailSettingsSectionGroup; 
0
private void button1_Click(object sender, EventArgs e) 
{ 
    try 
    { 
     var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 

     var mailSettings = config.GetSectionGroup("system.net/mailSettings") 
      as MailSettingsSectionGroup; 
     MailMessage msg = new MailMessage(); 
     msg.Subject = "Hi Raju"; 
     msg.To.Add("[email protected]"); 
     msg.From = new MailAddress("[email protected]"); 
     msg.Body = "Hello Raju here everything is fine."; 
     //MailSettingsSectionGroup msetting = null; 
     string mMailHost = mailSettings.Smtp.Network.Host; 

     SmtpClient mailClient = new SmtpClient(mMailHost); 
     mailClient.Send(msg); 
     MessageBox.Show("Mail Sent Succesfully..."); 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.ToString()); 
    } 
} 
関連する問題