Update app.config system.net setting at runtime

后端 未结 3 592
抹茶落季
抹茶落季 2020-11-29 04:06

I need to update a setting in the system.net SectionGroup of a .Net exe app.config file at runtime. I don\'t have write access to the original config file at runtime (I am d

3条回答
  •  Happy的楠姐
    2020-11-29 04:35

    I did not understand from your question if you don't have access to the app.config file because of your own design implementation or you just weren't able to save the config file, so here is a piece of code that allows you to modify and save appSettings section in the config file at runtime:

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    KeyValueConfigurationCollection settings = config.AppSettings.Settings;
    
    // update SaveBeforeExit
    settings[-keyname-].Value = "newkeyvalue";
    ...
    //save the file
    config.Save(ConfigurationSaveMode.Modified);
    //relaod the section you modified
    ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
    

    P.S the code will not save the app.config file you see in the solution editor, it will pdate the "program_name.exe.config" file in the operation forlder.

提交回复
热议问题