c# - 将 ConfigurationManager 重定向到另一个文件

标签 c# configuration internals

我希望将标准 .Net ConfigurationManager 类重定向到另一个文件; 完全。该路径是在运行时确定的,因此我不能使用 configSource 或类似的(这不是重复的问题 - 我已经看过其他问题)。

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

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

最佳答案

我终于明白了。有一个公开的记录方法可以做到这一点 - 但它隐藏在 .Net 框架的深处。更改您自己的配置文件需要反射(只是刷新 ConfigurationManager);但可以更改您通过公共(public) 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

关于c# - 将 ConfigurationManager 重定向到另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1194876/

相关文章:

C# const 保护与内部

r - retracemem在R中做什么?

java - JVM 如何实现可变参数?

c# - 基于参数抛出/不抛出异常 - 为什么这不是一个好主意?

c# - 在 app.config 中存储树状信息的最佳方式

c# - 如何在 Entity Framework 中用 Enum 替换 Int 属性?

Apache 服务器 ubuntu 10.10 返回要下载的 PHTML 文件而不是 php 文件

.net-core - "MCD"命令创建的 `dotnet publish` 配置是什么?

c# - 插入/更新大量记录 SQL Server

c# - 如何在 Visual C# 2008 Express 中的调试/发布之间切换