简体   繁体   中英

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

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

<system.net>
  <mailSettings>
    <smtp from="restore@example.com">
     <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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM