2

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;
  }
Brian
  • 5,069
  • 7
  • 37
  • 47
hong pei
  • 929
  • 2
  • 13
  • 27
  • Try this answer -- it worked for me: http://stackoverflow.com/a/6151688/67038 I ended up adapting the code a bit, and wrote an extension method for ApplicationSettingsBase – JMarsch Feb 27 '13 at 18:14
  • The most obvious thing I see is you never load the document. You just set the location of the file which isn't where it would be in a real situation anyways. – Security Hound Feb 27 '13 at 18:27
  • Possible duplicate of [Change default app.config at runtime](http://stackoverflow.com/questions/6150644/change-default-app-config-at-runtime) – Keith Hall Dec 30 '15 at 14:19

1 Answers1

6

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);
}
Community
  • 1
  • 1
Nick Bray
  • 1,953
  • 12
  • 18