【问题标题】:Redirect ConfigurationManager to Another File将 ConfigurationManager 重定向到另一个文件
【发布时间】:2010-11-14 18:11:15
【问题描述】:

我希望将 standard .Net ConfigurationManager 类重定向到另一个文件; 完全。路径是在运行时确定的,所以 我不能使用 configSource 之类的(这不是重复的问题 - 我已经查看了其他问题)。

我实际上是在尝试复制 ASP.Net 在幕后所做的事情。因此,不仅我的类应该从新的配置文件中读取,而且任何标准的 .Net 东西(我特别想开始工作的是 system.codeDom 元素)。

我已经破解了打开的 Reflector 并开始研究 ASP.Net 是如何做到的——它非常麻烦而且完全没有文档记录。我希望其他人对这个过程进行了逆向工程。不一定要寻找完整的解决方案(会很好),而只是文档

【问题讨论】:

    标签: c# configuration internals


    【解决方案1】:

    我终于明白了。有一种公开的记录 方法可以做到这一点 - 但它隐藏在 .Net 框架的深处。更改您自己的配置文件需要反射(仅刷新 ConfigurationManager);但可以更改您通过公共 API 创建的 AppDomain 的配置文件。

    感谢我提交的 Microsoft Connect 功能,这里是代码:

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

    输出:

    customDomain: C:\my.config
    InternalConfigTest.vshost.exe: D:\Profile\...\InternalConfigTest.vshost.exe.config
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-01
      • 1970-01-01
      • 2018-10-13
      • 2018-05-13
      • 2021-05-26
      相关资源
      最近更新 更多