且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否有可能切换应用程序配置文件在运行时.NET应用程序?

更新时间:2023-10-13 10:17:16

以上所有的工作做好,如果你需要更换只的AppSettings部分。

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