如何以编程方式将 SMTP 服务器详细信息存储(保存)回 web.config

Pre*_*zel 4 asp.net web-config system.net.mail

搜索 StackOverflow,我发现了有关如何从 Web.Config 检索 SMTP 设置的问题,但没有有关如何将 SMTP 更新回 web.config 文件的详细信息。

我从以下代码开始:

Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("~");
MailSettingsSectionGroup settings =
  (MailSettingsSectionGroup)webConfig.GetSectionGroup("system.net/mailSettings");
SmtpSection smtp = settings.Smtp;
SmtpNetworkElement net = smtp.Network;
Run Code Online (Sandbox Code Playgroud)

但很快就被 Intellisense 发现了,这SmptSection.Network是一个 Get(又名“只读”)访问器。

那么我应该如何以编程方式将 SMTP 数据写回 web.config 呢?

Col*_*ard 6

你应该能够做这样的事情,这有效吗?:

Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("~");
MailSettingsSectionGroup settings =
    (MailSettingsSectionGroup)webConfig.GetSectionGroup("system.net/mailSettings");
SmtpSection smtp = settings.Smtp;
SmtpNetworkElement net = smtp.Network;
net.Port = 25;
net.Host = "localhost";
webConfig.Save();
Run Code Online (Sandbox Code Playgroud)