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?
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.