ConfigurationManager добавляет неожиданные элементы в раздел system.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 не создавал эти разделы. Как это сделать?

Спасибо


person Davi Fiamenghi    schedule 03.12.2012    source источник


Ответы (1)


Быстрым решением было бы очистить его вручную в XML после того, как ConfigurationManager загрязнит файл, но я думаю, что это не самое подходящее решение.

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);
person Davi Fiamenghi    schedule 03.12.2012