Is it possible to switch application configuration file at runtime for .NET application?

前端 未结 4 1458
一个人的身影
一个人的身影 2020-12-29 13:06

By default, .NET application\'s configuration file is named after \"exe file name\".config. I\'m wondering whether it is possible to have one application\'s configuration sp

4条回答
  •  情书的邮戳
    2020-12-29 13:44

    All of the above work well if you need to replace only AppSettings section.

    In case you have to run with different config files (all sections) you might want to consider launching application using a host, that creates app domain for your main application and sets different config file depending on parameters you passed in.

    Here's the code that worked for me:

            AppDomainSetup setup = new AppDomainSetup();
            setup.ApplicationBase = "file://" + System.Environment.CurrentDirectory;
            setup.DisallowBindingRedirects = true;
            setup.DisallowCodeDownload = true;
    
            if (args.Length != 0 && args[0].Equals("-test"))
            {
                setup.ConfigurationFile = "PATH_TO_YOUR_TEST_CONFIG_FILE";
            }
            else {
                setup.ConfigurationFile = "PATH_TO_YOUR_LIVE_CONFIG_FILE";
            }
    
            AppDomain domain = AppDomain.CreateDomain("FRIENDLY_NAME", null, setup);
            domain.ExecuteAssembly("YourMainApp.exe");
    

提交回复
热议问题