7

Is there any way that I could specify at runtime the configuration file I would like to use (other than App.config)? For example I would like to read a first argument from a command line that will be a path to the application's config and I would like my application to refer to it when I use ConfigurationManager.AppSettings (It's probably impossible but still it's worth asking).
I did find this piece of code:

System.Configuration.Configuration config
    = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        config.AppSettings.File = myRuntimeConfigFilePath;
        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("appSettings");

It works, but it overrides the original App.config's AppSettings section and my application isn't supposed to write anything.

agnieszka
  • 14,897
  • 30
  • 95
  • 113

4 Answers4

9

I found this and it works. "path" is a path to configuration file.

AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path);
agnieszka
  • 14,897
  • 30
  • 95
  • 113
4

Not directly.

Indirectly, you could:

  • spin up a second AppDomain, specify the config-file for that (AppDomainSetup.ConfigurationFile), and execute the code in the app domain
  • have two exes; the first (foo.exe) simply copies the config (into bar.exe.config) and shells the 2nd exe (bar.exe) [warning: thread race]
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • That is a big topic... basically, in .NET you have a level of abstraction inside a Process - the AppDomain. See msdn: http://msdn.microsoft.com/en-us/library/yb506139.aspx – Marc Gravell Feb 10 '09 at 11:45
0

If you're using log4net you can specify your configuration file in the AssemblyInfo.cs

Scott Cowan
  • 2,652
  • 7
  • 29
  • 45
0

Another solution is to refactor and create your own ConfigurationRepository. Then you can change at runtime what specific repository implementation you will use.

For example, AppConfigRepository : ConfigurationRespository will just be a facade for the old ConfigurationManager.AppSettings["key"].

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
ThorHalvor
  • 628
  • 5
  • 17
  • I already know about it but i'm looking for something simpler so that I don't reinvent the wheel (if it exists ;)) – agnieszka Feb 10 '09 at 11:40