Programmatic access to arbitrary web.config - cannot access appSettings (app.config is ok)

I am accessing the configuration file:

var map = new ConfigurationFileMap(configPath); var config = ConfigurationManager.OpenMappedMachineConfiguration(map); config.AppSettings.Settings.Add("SomeSetting", "SomeValue"); 

It works fine for any .exe.config file, but not for any web.config.

Note. I am not trying to access the web.config of the current application, I am trying to modify the web.config file on an arbitrary path.

(I tried WebConfigurationManager instead of ConfigurationManager , but it gives the same results)

An exception is AppSettings attribute of the AppSettings property - when trying to GetSection("appSettings") and throws it into the AppSettingsSection , of course, the same exception. Anyway, here it is:

 System.InvalidCastException: Unable to cast object of type 'System.Configuration.DefaultSection' to type 'System.Configuration.AppSettingsSection'. 

I obviously searched, but found only users who turned to web.config for the "current web application" or using XmlDocument / XDocument .

My guess is that the .exe.config files automatically receive certain information like configSections, which means that it correctly knows how to handle appSettings. However, I have no idea why, based on the file name, it will not work with web.config.


Oh. For app.config, I am using OpenExeConfiguration:

 // works fine for .exe.config var config = ConfigurationManager.OpenExeConfiguration("some-assembly-here.exe"); config.AppSettings.Settings.Add("SomeSetting", "SomeValue"); config.Save(); 

Here I use OpenMappedMachineConfiguration , which seems to be for machine.config, however I don't see another way to open an arbitrary web.config file - anyone?

+6
source share
1 answer

My mistake. I can use OpenMappedExeConfiguration only when opening web.config files:

  var map = new ExeConfigurationFileMap(); map.ExeConfigFilename = configPath; var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); 
+9
source

Source: https://habr.com/ru/post/902400/


All Articles