我希望将标准 .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/