Saving to mailSettings in App.Config in .net wf application

2k views Asked by At

I'm trying to save from a windows form to the following settings in app.config

<system.net>
  <mailSettings>
    <smtp from="[email protected]">
     <network host="smtp" port="25" defaultCredentials="true"/>
    </smtp>
  </mailSettings>
</system.net>

I am trying to use the code below to set that, however I am getting the error that the configuration is read only.

private void SaveMailSettings()
{
    var smtpSection = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection;
    try
    {
        if (smtpSection == null) return;
        smtpSection.Network.Host = txtSmtpHost.Text;
        smtpSection.Network.Port = Convert.ToInt32(txtSmtpPort.Text);
        smtpSection.From = txtSmtpFrom.Text;
        if (smtpSection.Network.UserName != null) smtpSection.Network.UserName = txtSmtpUserName.Text;
        if (smtpSection.Network.Password != null) smtpSection.Network.Password = txtSmtpPassword.Text;
        Logger.Log(string.Format("Host: {0}, Port: {1}, From: {2}, UserName: {3}, Password: {4}", smtpSection.Network.Host, smtpSection.Network.Port, smtpSection.Network.UserName, smtpSection.Network.Password), "INFO");
     }
     catch (Exception ex)
     {
         Logger.Log(ex.Message, "ERROR:");
     }
}

Is there any way I can update the App.Config file mailSettings?

1

There are 1 answers

1
farid bekran On BEST ANSWER

You cannot edit configuration file via ConfigurationManager.GetSection

You should Open file and make changes and save the file.

Note: Don't test this in debug mode. I don't know why changes not saving in debug mode. But when normally run the .exe file changes saved.

var webConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings =(MailSettingsSectionGroup)webConfig.GetSectionGroup("system.net/mailSettings");
webConfig.AppSettings.Settings["test"].Value = "asdad";
SmtpSection smtp = settings.Smtp;
SmtpNetworkElement net = smtp.Network;
net.Port = 2005;
net.Host = "localhostEditedEdited";
webConfig.Save(ConfigurationSaveMode.Modified);