c# - Is it possible to make the app settings editable by using reflection to adjust the readonly attribute? -


i found following code set readonly attribute false configurationmanager.connectionstrings property:

    typeof(configurationelementcollection)         .getfield("breadonly", bindingflags.instance | bindingflags.nonpublic)         .setvalue(configurationmanager.connectionstrings, false); 

is possible apply make appsettings property editable?

appsettings namevaluecollection implements nameobjectcollectionbase has isreadonly property on it. if call getfields() returns empty list.

edit:

what trying modify appsettings in unit test, execute method read app settings , perform functions.

so option allows me change appsettings in memory (but not persist them disk) work. ideally, without recycling app pool.

it works connection strings, unable app settings editable using same technique.

if want update setting in appsettings section of *.config file , persist it, the code below should trick.

private void updatesetting(string key, string value) {     var configuration = configurationmanager        .openexeconfiguration(assembly.getexecutingassembly().location);      configuration.appsettings.settings[key].value = value;      configuration.save(configurationsavemode.modified);     configurationmanager.refreshsection("appsettings");      // need update setting in memory     updatesettinginmemory(key, value); }  private void updatesettinginmemory(string key, string value) {     var configuration = configurationmanager         .openexeconfiguration(configurationuserlevel.none);      configuration.appsettings.settings[key].value = value;      configuration.save(configurationsavemode.modified);      configurationmanager.refreshsection("appsettings"); } 

Comments