Search code examples
asp.netweb-configglobal-asaxdirectorydirectory-structure

Read values from non-root web.config file


My site is structured in this way:

  • Root Directory
    • Arcade
      • default.aspx
      • web.config
    • default.aspx
    • web.config

I have a method Method1() which accesses:

System.Configuration.ConfigurationManager.AppSettings["Total_Unique_Plays_Required_For_High_Score_Board"]

This value exists in the root/Arcade/Web.config file but not in the root/web.config file.

When I execute Method1() from a page in the /arcade directory it works fine. However, when I execute this method as a timed event from global.asax it searches for the value in the root web.config file and throws a System.NullException.

Does anyone know how I can specify to search for the value in the root/arcade/web.config file and not the root/web.config file?


Solution

  • You can open the web.config file first.

    So calling this will load your child file; notice you give the path to the folder containing the web.config, not the actual config file.

    var config = WebConfigurationManager.OpenWebConfiguration("~/Arcade");
    

    You can now get your values, like:

    string MyValue  = config.AppSettings.Settings["MySetting"].Value;
    

    You can also get the list of app settings by calling:

    KeyValueConfigurationCollection appSettings = config.AppSettings.Settings;