ConfigurationManager将意外的项添加到system.web部分

时间:2012-12-03 20:45:54

标签: configurationmanager system.web

我正在Web安装程序自定义操作期间修改Web.config文件上的连接字符串。

这是正在完成工作的代码片段

ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = path;

Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, System.Configuration.ConfigurationUserLevel.None);

var connectionsection = config.ConnectionStrings.ConnectionStrings;

ConnectionStringSettings connectionstring = connectionsection[connStringName];
if (connectionsection != null)
    connectionsection.Remove(connStringName);

connectionstring = new ConnectionStringSettings(connStringName, newValue, "System.Data.SqlClient");
connectionsection.Add(connectionstring);

config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");

到目前为止一切顺利,这实际上是有效的,但它也在“system.web”部分添加了一些项目,导致错误:

Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. 

Parser Error Message: It is an error to use a section registered as allowDefinition='MachineOnly' beyond machine.config.
Source Error: 

Line 46:     <authorization />
Line 47:     <clientTarget />
Line 48:     <deployment />
Line 49:     <deviceFilters />
Line 50:     <fullTrustAssemblies />

当我手动删除ConfigurationManager <deployment /><protocols /><processModel />添加的某些部分时,错误消失了。所以我只需要ConfigurationManager就不要创建这个部分。怎么做?

由于

1 个答案:

答案 0 :(得分:0)

在ConfigurationManager弄脏文件后,快速修复将在XML中手动清除,但这不是最合适的,我认为

config.Save(ConfigurationSaveMode.Modified, true);

var document = XDocument.Load(configPath);
var systemWeb = document.Root.Element("system.web");

XElement element;
element = systemWeb.Element("deployment");
if (element != null)
    element.Remove();

element = systemWeb.Element("protocols");
if (element != null)
    element.Remove();

element = systemWeb.Element("processModel");
if (element != null)
    element.Remove();

document.Save(configPath);