首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在mailSettings应用程序中在App.Config中保存到.net

在mailSettings应用程序中在App.Config中保存到.net
EN

Stack Overflow用户
提问于 2015-06-21 07:46:19
回答 1查看 1.9K关注 0票数 2

我正试图从windows窗体保存到app.config中的下列设置

代码语言:javascript
复制
<system.net>
  <mailSettings>
    <smtp from="restore@example.com">
     <network host="smtp" port="25" defaultCredentials="true"/>
    </smtp>
  </mailSettings>
</system.net>

我试图使用下面的代码来设置它,但是我得到的错误是配置是只读的。

代码语言:javascript
复制
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:");
     }
}

有什么方法可以更新App.Config文件mailSettings吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-21 10:32:18

您不能通过ConfigurationManager.GetSection编辑配置文件。

您应该打开文件并进行更改并保存该文件。

注意:不要在调试模式下对此进行测试。我不知道为什么在调试模式下更改不保存。但是,当正常运行.exe文件时,保存的.文件更改。

代码语言:javascript
复制
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);
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30962347

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档