I'm accessing a config file thusly:
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 attempting to modify the web.config in an arbitrary path.
(I've tried WebConfigurationManager
instead of ConfigurationManager
, but it gives identical results)
The exception is thrown by the AppSettings
property accessor - trying to GetSection("appSettings")
and cast it to an AppSettingsSection
of course gievs the same exception. Either way, here it is:
System.InvalidCastException: Unable to cast object of type 'System.Configuration.DefaultSection' to type 'System.Configuration.AppSettingsSection'.
I have obviously searched around, but have found only people accessing the web.config for the 'current web app' or using XmlDocument
/XDocument
.
My guess is .exe.config files automatically get some configSections-type information inferred which means it correctly knows how to deal with appSettings. However I have no idea why, based on the filename, it wouldn't work with web.config.
Ah. For app.config I'm 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'm using OpenMappedMachineConfiguration
which appears to be for machine.config, however I can't see another way of opening an arbitrary web.config file - anyone?
My mistake - I can use OpenMappedExeConfiguration
just fine when opening web.config files:
var map = new ExeConfigurationFileMap();
map.ExeConfigFilename = configPath;
var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With