137

I have the following problem:
We have an application that loads modules (add ons). These modules might need entries in the app.config (e.g. WCF configuration). Because the modules are loaded dynamically, I don't want to have these entries in the app.config file of my application.
What I would like to do is the following:

  • Create a new app.config in memory that incorporates the config sections from the modules
  • Tell my application to use that new app.config

Note: I do not want to overwrite the default app.config!

It should work transparently, so that for example ConfigurationManager.AppSettings uses that new file.

During my evaluation of this problem, I came up with the same solution as is provided here: Reload app.config with nunit.
Unfortunately, it doesn't seem to do anything, because I still get the data from the normal app.config.

I used this code to test it:

Console.WriteLine(ConfigurationManager.AppSettings["SettingA"]);
Console.WriteLine(Settings.Default.Setting);

var combinedConfig = string.Format(CONFIG2, CONFIG);
var tempFileName = Path.GetTempFileName();
using (var writer = new StreamWriter(tempFileName))
{
    writer.Write(combinedConfig);
}

using(AppConfig.Change(tempFileName))
{
    Console.WriteLine(ConfigurationManager.AppSettings["SettingA"]);
    Console.WriteLine(Settings.Default.Setting);
}

It prints the same values twices, although combinedConfig contains other values than the normal app.config.

9
  • Hosting the modules in separate AppDomain with the appropriate configuration file is not an option? May 27, 2011 at 10:36
  • Not really, because that would result in lots of Cross-AppDomain calls, because the application interacts quite heavily with the modules. May 27, 2011 at 10:37
  • How about an application restart when a new module needs to be loaded? May 27, 2011 at 10:47
  • This doesn't work together with the business requirements. Furthermore, I can't overwrite the app.config, because the user doesn't have the right to do so. May 27, 2011 at 10:48
  • You would be reloading to load a different App.config, not the one in program files. The hack in Reload app.config with nunit could work, not sure, if used on application entry before any configuration is loaded. May 27, 2011 at 10:51

8 Answers 8

295

The hack in the linked question works if it is used before the configuration system is used the first time. After that, it doesn't work any more.
The reason:
There exists a class ClientConfigPaths that caches the paths. So, even after changing the path with SetData, it is not re-read, because there already exist cached values. The solution is to remove these, too:

using System;
using System.Configuration;
using System.Linq;
using System.Reflection;

public abstract class AppConfig : IDisposable
{
    public static AppConfig Change(string path)
    {
        return new ChangeAppConfig(path);
    }

    public abstract void Dispose();

    private class ChangeAppConfig : AppConfig
    {
        private readonly string oldConfig =
            AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString();

        private bool disposedValue;

        public ChangeAppConfig(string path)
        {
            AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path);
            ResetConfigMechanism();
        }

        public override void Dispose()
        {
            if (!disposedValue)
            {
                AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", oldConfig);
                ResetConfigMechanism();


                disposedValue = true;
            }
            GC.SuppressFinalize(this);
        }

        private static void ResetConfigMechanism()
        {
            typeof(ConfigurationManager)
                .GetField("s_initState", BindingFlags.NonPublic | 
                                         BindingFlags.Static)
                .SetValue(null, 0);

            typeof(ConfigurationManager)
                .GetField("s_configSystem", BindingFlags.NonPublic | 
                                            BindingFlags.Static)
                .SetValue(null, null);

            typeof(ConfigurationManager)
                .Assembly.GetTypes()
                .Where(x => x.FullName == 
                            "System.Configuration.ClientConfigPaths")
                .First()
                .GetField("s_current", BindingFlags.NonPublic | 
                                       BindingFlags.Static)
                .SetValue(null, null);
        }
    }
}

Usage is like this:

// the default app.config is used.
using(AppConfig.Change(tempFileName))
{
    // the app.config in tempFileName is used
}
// the default app.config is used.

If you want to change the used app.config for the whole runtime of your application, simply put AppConfig.Change(tempFileName) without the using somewhere at the start of your application.

30
  • 3
    @Daniel That was awesome -- I worked it into an exentension method for ApplicationSettingsBase, so that I can call Settings.Default.RedirectAppConfig(path). I'd give you +2 if I could!
    – JMarsch
    Feb 14, 2013 at 17:50
  • 2
    @PhilWhittington: That's what I am saying, yes. Aug 6, 2013 at 12:33
  • 2
    out of interest, is there any reason to suppress the finalizer is there is no finalizer declared?
    – Gusdor
    Apr 1, 2014 at 10:19
  • 2
    @DanielHilgarth The standard pattern of implementing Dispose calls GC.SuppressFinalize involves a Dispose() non-virtual method, and a Dispose(bool) virtual method. You aren't actually using the standard Dispose pattern. Anyway, the point of the GC.SuppressFinalize even if the base class has no finalizer is because a derived class might, but unless you actually want to support other classes deriving from AppConfig, there is no benefit to it. In fact, I would give AppConfig a private constructor precisely so that other classes cannot use it as a base.
    – user743382
    Mar 17, 2015 at 9:35
  • 3
    That aside, using reflection to access private fields may work now, but it could use a warning that it isn't supported and may break in future versions of the .NET Framework.
    – user743382
    Mar 17, 2015 at 9:36
11

You can try to use Configuration and Add ConfigurationSection on runtime

Configuration applicationConfiguration = ConfigurationManager.OpenMappedExeConfiguration(
                        new ExeConfigurationFileMap(){ExeConfigFilename = path_to_your_config,
                        ConfigurationUserLevel.None
                        );

applicationConfiguration.Sections.Add("section",new YourSection())
applicationConfiguration.Save(ConfigurationSaveMode.Full,true);

EDIT: Here is solution based on reflection (not very nice though)

Create class derived from IInternalConfigSystem

public class ConfigeSystem: IInternalConfigSystem
{
    public NameValueCollection Settings = new NameValueCollection();
    #region Implementation of IInternalConfigSystem

    public object GetSection(string configKey)
    {
        return Settings;
    }

    public void RefreshConfig(string sectionName)
    {
        //throw new NotImplementedException();
    }

    public bool SupportsUserConfig { get; private set; }

    #endregion
}

then via reflection set it to private field in ConfigurationManager

        ConfigeSystem configSystem = new ConfigeSystem();
        configSystem.Settings.Add("s1","S");

        Type type = typeof(ConfigurationManager);
        FieldInfo info = type.GetField("s_configSystem", BindingFlags.NonPublic | BindingFlags.Static);
        info.SetValue(null, configSystem);

        bool res = ConfigurationManager.AppSettings["s1"] == "S"; // return true
6
  • I don't see how this helps me. This will add a section to the file specified by file_path. This will not make the section available to users of ConfigurationManager.GetSection, because GetSection uses the default app.config. May 27, 2011 at 10:13
  • You can add Sections to your existing app.config. Just tried this - works for me
    – Stecya
    May 27, 2011 at 10:24
  • Quote from my question: "Note: I do not want to overwrite the default app.config!" May 27, 2011 at 10:26
  • 5
    What's wrong? Simple: The user has no right to overwrite it, because the program is installed in %ProgramFiles% and the user is no administrator. May 27, 2011 at 10:33
  • 2
    @Stecya: Thanks for your effort. But please see my answer for the real solution to the problem. May 27, 2011 at 11:35
5

@Daniel solution works OK. A similar solution with more explanation is in c-sharp corner. For completeness I'd like to share my version: with using, and the bit flags abbreviated.

using System;//AppDomain
using System.Linq;//Where
using System.Configuration;//app.config
using System.Reflection;//BindingFlags

    /// <summary>
    /// Use your own App.Config file instead of the default.
    /// </summary>
    /// <param name="NewAppConfigFullPathName"></param>
    public static void ChangeAppConfig(string NewAppConfigFullPathName)
    {
        AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", NewAppConfigFullPathName);
        ResetConfigMechanism();
        return;
    }

    /// <summary>
    /// Remove cached values from ClientConfigPaths.
    /// Call this after changing path to App.Config.
    /// </summary>
    private static void ResetConfigMechanism()
    {
        BindingFlags Flags = BindingFlags.NonPublic | BindingFlags.Static;
        typeof(ConfigurationManager)
            .GetField("s_initState", Flags)
            .SetValue(null, 0);

        typeof(ConfigurationManager)
            .GetField("s_configSystem", Flags)
            .SetValue(null, null);

        typeof(ConfigurationManager)
            .Assembly.GetTypes()
            .Where(x => x.FullName == "System.Configuration.ClientConfigPaths")
            .First()
            .GetField("s_current", Flags)
            .SetValue(null, null);
        return;
    }
5

If anybody is interested, here is a method that works on Mono.

string configFilePath = ".../App";
System.Configuration.Configuration newConfiguration = ConfigurationManager.OpenExeConfiguration(configFilePath);
FieldInfo configSystemField = typeof(ConfigurationManager).GetField("configSystem", BindingFlags.NonPublic | BindingFlags.Static);
object configSystem = configSystemField.GetValue(null);
FieldInfo cfgField = configSystem.GetType().GetField("cfg", BindingFlags.Instance | BindingFlags.NonPublic);
cfgField.SetValue(configSystem, newConfiguration);
3

Daniel's solution seems to work even for downstream assemblies I had used AppDomain.SetData before, but was unaware of how to reset the internal configuration flags

Converted to C++/CLI for those interested

/// <summary>
/// Remove cached values from ClientConfigPaths.
/// Call this after changing path to App.Config.
/// </summary>
void ResetConfigMechanism()
{
    BindingFlags Flags = BindingFlags::NonPublic | BindingFlags::Static;
    Type ^cfgType = ConfigurationManager::typeid;

    Int32 ^zero = gcnew Int32(0);
    cfgType->GetField("s_initState", Flags)
        ->SetValue(nullptr, zero);

    cfgType->GetField("s_configSystem", Flags)
        ->SetValue(nullptr, nullptr);

    for each(System::Type ^t in cfgType->Assembly->GetTypes())
    {
        if (t->FullName == "System.Configuration.ClientConfigPaths")
        {
            t->GetField("s_current", Flags)->SetValue(nullptr, nullptr);
        }
    }

    return;
}

/// <summary>
/// Use your own App.Config file instead of the default.
/// </summary>
/// <param name="NewAppConfigFullPathName"></param>
void ChangeAppConfig(String ^NewAppConfigFullPathName)
{
    AppDomain::CurrentDomain->SetData(L"APP_CONFIG_FILE", NewAppConfigFullPathName);
    ResetConfigMechanism();
    return;
}
3

Wonderful discussion, I've adding more comments to ResetConfigMechanism method to understand the magic behind the statement/calls in the method. Also added file path exist check

using System;//AppDomain
using System.Linq;//Where
using System.Configuration;//app.config
using System.Reflection;//BindingFlags
using System.Io;

/// <summary>
/// Use your own App.Config file instead of the default.
/// </summary>
/// <param name="NewAppConfigFullPathName"></param>
public static void ChangeAppConfig(string NewAppConfigFullPathName)
{
    if(File.Exists(NewAppConfigFullPathName)
    {
      AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", 
      NewAppConfigFullPathName);
      ResetConfigMechanism();
      return;
    }
}

/// <summary>
/// Remove cached values from ClientConfigPaths.
/// Call this after changing path to App.Config.
/// </summary>
private static void ResetConfigMechanism()
{
    BindingFlags Flags = BindingFlags.NonPublic | BindingFlags.Static;
      /* s_initState holds one of the four internal configuration state.
          0 - Not Started, 1 - Started, 2 - Usable, 3- Complete

         Setting to 0 indicates the configuration is not started, this will 
         hint the AppDomain to reaload the most recent config file set thru 
         .SetData call
         More [here][1]

      */
    typeof(ConfigurationManager)
        .GetField("s_initState", Flags)
        .SetValue(null, 0);


    /*s_configSystem holds the configuration section, this needs to be set 
        as null to enable reload*/
    typeof(ConfigurationManager)
        .GetField("s_configSystem", Flags)
        .SetValue(null, null);

      /*s_current holds the cached configuration file path, this needs to be 
         made null to fetch the latest file from the path provided 
        */
    typeof(ConfigurationManager)
        .Assembly.GetTypes()
        .Where(x => x.FullName == "System.Configuration.ClientConfigPaths")
        .First()
        .GetField("s_current", Flags)
        .SetValue(null, null);
    return;
}
1

If your config file is just written with key/values in "appSettings", then you can read another file with such code :

System.Configuration.ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = configFilePath;

System.Configuration.Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
AppSettingsSection section = (AppSettingsSection)configuration.GetSection("appSettings");

Then you can read section.Settings as collection of KeyValueConfigurationElement.

3
  • 1
    As I already said, I want to make ConfigurationManager.GetSection read the new file I created. Your solution doesn't do that. May 27, 2011 at 10:42
  • @Daniel : why ? You can specify any file in "configFilePath". So you just need to know the location of your new created file. Did I miss something ? Or you really need to use "ConfigurationManager.GetSection" and nothing else ?
    – Ron
    May 27, 2011 at 10:43
  • 1
    Yes you do miss something: ConfigurationManager.GetSection uses the default app.config. It doesn't care about the config file you opened with OpenMappedExeConfiguration. May 27, 2011 at 10:45
0

Daniel, if possible try to use other config mechanisms. We have been through this route where we had different static/dynamic config files depending on environment/profile/group and it became quite messy at the end.

you could try out some sort of Profile WebService where you only specify one Web Service URL from the client and depending on Client's details (you might have Group/User level overrides), it loads up all the config it needs. We have also used MS Enterprise Library for some part of it.

that was you dont deploy config with your client and you can manage it separately from your clients

1
  • 3
    Thanks for your answer. However, the whole reason of this is to avoid shipping config files. The configuration details for the modules are loaded from a database. But because I want to give module developers the comfort of the default .NET configuration mechanism, I want to incorporate those module configurations into one config file at runtime and make this the default config file. The reason is simple: There exist a lot of libraries that can be configured through app.config (e.g. WCF, EntLib, EF, ...). If I would introduce another config mechanism, the configuration would (cont.) May 27, 2011 at 10:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.