Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect ConfigurationManager to Another File

I am looking to redirect the standard .Net ConfigurationManager class to another file; entirely. The path is determined at runtime so I can't use configSource or such (this is not a duplicate question - I have looked at the others).

I am essentially trying to duplicate what ASP.Net is doing behind the covers. Thus not only my classes should read from the new config file, but also any standard .Net stuff (the one I am specifically trying to get to work is the system.codeDom element).

I have cracked open Reflector and started looking at how ASP.Net does it - it's pretty hairy and completely undocumented. I was hoping someone else has reverse-engineered the process. Not necessarily looking for a complete solution (would be nice) but merely documentation.

like image 436
Jonathan C Dickinson Avatar asked Jul 28 '09 15:07

Jonathan C Dickinson


1 Answers

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
like image 60
Jonathan C Dickinson Avatar answered Oct 13 '22 19:10

Jonathan C Dickinson