hong pei
hong pei

Reputation: 929

How to use a specific app config file

The below code does not work. It does not get the app settings from the TestApp.Config file. Do you know why? And how can I fix it?

  public void GetConfig()
  {
     AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", @"C:\dev\VS\ProofOfConcept\ProofOfConcept\TestApp.config");
     var a = ConfigurationManager.AppSettings;
  }

Upvotes: 2

Views: 5065

Answers (1)

Nick Bray
Nick Bray

Reputation: 1963

This post might help:

In the solution posted here there is a method ResetConfigurationMechanism() that you should call after you call CurrentDomain.SetData(...);.

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);
}

Upvotes: 6

Related Questions