Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programatically access arbitrary web.config - can't access appSettings (app.config is fine)

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?

like image 212
Kieren Johnstone Avatar asked Nov 25 '11 15:11

Kieren Johnstone


1 Answers

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);
like image 85
Kieren Johnstone Avatar answered Nov 05 '22 05:11

Kieren Johnstone