Using configurationmanager to read from multiple web.config files

Steve's a D picture Steve's a D · Aug 21, 2012 · Viewed 8k times · Source

Background:

I have some data thats stored in the web.config files of about 100 web applications. This data is getting moved to a database gradually. The webpages will show the web.config data until somebody clicks on an "edit" link in which case they'll be redirected to a webpage which will allow them to update this data where it will be saved in a database instead.

Problem:

Not all of the data will be changed on this page that will save it to the database. When somebody clicks the "edit" link I want the form to populate with the data from the web.config file and when they click "save" have it save to the database. However, using the configurationmanager I can only get it to pull data from the web.config file on current application.

Questions:

  1. Is there a way to use configurationmanager to select the web.config file from lets say ../{dynamic_app_id}/web.config ?
  2. is reading them as plain xml files my only option?
  3. Are there any pitfalls to this approach?
  4. Is there another solution that would work better perhaps?

Answer

Gregor Primar picture Gregor Primar · Aug 21, 2012

You can read any config file with ease. Please see my sample code where I read application settings from external app.config file:

        System.Configuration.KeyValueConfigurationCollection settings;
        System.Configuration.Configuration config;

        System.Configuration.ExeConfigurationFileMap configFile = new System.Configuration.ExeConfigurationFileMap();
        configFile.ExeConfigFilename = "my_file.config";
        config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(configFile, System.Configuration.ConfigurationUserLevel.None);
        settings = config.AppSettings.Settings;

Happy coding and best regards!