Redirect ConfigurationManager to Another File

社会主义新天地 提交于 2019-12-03 08:05:47

I finally figured it out. There is a public documented means to do this - but it's hidden away in the depths of the .Net framework. Changing your own config file requires reflection (to do no more than refresh the ConfigurationManager); but it is possible to alter the configuration file of an AppDomain that you create via public APIs.

No thanks to the Microsoft Connect feature I submitted, here is the code:

class Program
{
    static void Main(string[] args)
    {
        // Setup information for the new appdomain.
        AppDomainSetup setup = new AppDomainSetup();
        setup.ConfigurationFile = "C:\\my.config";

        // Create the new appdomain with the new config.
        AppDomain d2 = AppDomain.CreateDomain("customDomain", AppDomain.CurrentDomain.Evidence, setup);

        // Call the write config method in that appdomain.
        CrossAppDomainDelegate del = new CrossAppDomainDelegate(WriteConfig);
        d2.DoCallBack(del);

        // Call the write config in our appdomain.
        WriteConfig();

        Console.ReadLine();
    }

    static void WriteConfig()
    {
        // Get our config file.
        Configuration c = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        // Write it out.
        Console.WriteLine("{0}: {1}", AppDomain.CurrentDomain.FriendlyName, c.FilePath);
    }
}

Output:

customDomain: C:\my.config
InternalConfigTest.vshost.exe: D:\Profile\...\InternalConfigTest.vshost.exe.config
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!