How to programmatically store (save) SMTP server d

2019-05-09 02:32发布

问题:

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