This is totally weird. Why does this code:
1 System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/web.config");
2 System.Net.Configuration.MailSettingsSectionGroup mailSection = config.GetSectionGroup("system.net/mailSettings") as System.Net.Configuration.MailSettingsSectionGroup;
3 mailSection.Smtp.From = tbMailFrom.Text;
4 mailSection.Smtp.Network.Host = tbMailServer.Text;
5 int mailPort = 25;
6 int.TryParse(tbMailPort.Text, out mailPort);
7 mailSection.Smtp.Network.Port = mailPort;
8 config.Save(ConfigurationSaveMode.Modified);
throw an exception at line 8:
System.Configuration.ConfigurationErrorsException: A configuration file cannot be created for the requested Configuration object. at System.Configuration.MgmtConfigurationRecord.SaveAs(String filename, ConfigurationSaveMode saveMode, Boolean forceUpdateAll) at System.Configuration.Configuration.SaveAsImpl(String filename, ConfigurationSaveMode saveMode, Boolean forceSaveAll) at System.Configuration.Configuration.Save(ConfigurationSaveMode saveMode) at Admin_EmailSettings.btnSaveEmailConfig_Click(Object sender, EventArgs e)
I'd love to use the built-in Configuration object offered by NET 2.0. I can read the config without any problem using this object, but I cannot save it!
If I pass null to WebConfigurationManager.OpenWebConfiguration(null), the code above works fine, but instead of updating my web-application's config it updates the file C:\WINNT\Microsoft.NET\Framework\v2.0.50727\CONFIG\web.config
The only solution I have found thus far is to update the web.config treating it as plain xml (and this works!):
1 System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
2 doc.Load(Server.MapPath("../web.config"));
3 string strSel = "/configuration/system.net/mailSettings";
4 System.Xml.XmlNode nodeMailSettingsOld = doc.SelectSingleNode(strSel);
5 // remove self
6 nodeMailSettingsOld.ParentNode.RemoveChild(nodeMailSettingsOld);
7 System.Xml.XmlNode nodeSystemNet = doc.SelectSingleNode("/configuration/system.net");
8 System.Xml.XmlNode nodeMailSettings = doc.CreateNode(System.Xml.XmlNodeType.Element, "mailSettings", null);
9 System.Xml.XmlNode nodeSmtp = doc.CreateNode(System.Xml.XmlNodeType.Element, "smtp", null);
10 System.Xml.XmlAttribute attFrom = doc.CreateAttribute("from");
11 attFrom.Value = tbMailFrom.Text;
12 nodeSmtp.Attributes.Append(attFrom);
13 nodeMailSettings.AppendChild(nodeSmtp);
14 nodeSystemNet.AppendChild(nodeMailSettings);
15 doc.Save(Server.MapPath("../web.config"));
I searched these forums to see if anybody encountered similar issues. Some posters reported identical exceptions (in ASP.NET Configuration web-tool) if web-app's path contained characters like &, #, etc. but this is not the case here: ASP.NET Configuration web-tool works fine and the only issue is that I cannot save modified configuration file via the Configuration object.
Any ideas?
Thank you!