How to programmatically store (save) SMTP server details back to web.config

痴心易碎 提交于 2019-12-07 09:31:48

问题


Searching StackOverflow, I found this question on how to Retrieve SMTP settings from Web.Config, but no details on how to update the SMTP back to the web.config file.

I started with the following code:

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

but was quickly clued in by Intellisense that SmptSection.Network is a Get (aka "read-only") accessor.

So how am I supposed to programmatically write my SMTP data back to web.config?


回答1:


You should be able to do something like this, does this work?:

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



回答2:


Take a look at this article: http://www.west-wind.com/WebLog/posts/8461.aspx

Looks like you need fairly high access (permissions) though.

Specifically from the article:

protected void Page_Load(object sender, EventArgs e)
{
    Configuration config = WebConfigurationManager.OpenWebConfiguration("~");

    wwDbResourceProviderSection Section = config.GetSection("wwDbResourceProvider") as wwDbResourceProviderSection;

    Section.ShowControlIcons = true;
    config.Save();

    return;
}


来源:https://stackoverflow.com/questions/4100215/how-to-programmatically-store-save-smtp-server-details-back-to-web-config

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!