2012-03-14 72 views
1

如果我有myprogram.exe.config文件:.Net配置 - 如何覆盖映射配置文件中的设置和自定义部分?

<configuration> 
    <configSections> 
    <section name="fooSection" type="MyNamespace.MySection, My.Assembly"/> 
    </configSections> 
    <appSettings> 
    <add key="foo" value="bar"/> 
    </appSettings> 
    <fooSection> 
    <bar> 
     <add baz="foo bar baz"/> 
    </bar> 
    </fooSection> 
</configuration> 

和我有overrides.config文件:

<configuration> 
    <configSections> 
    <section name="fooSection" type="MyNamespace.MySection, My.Assembly"/> 
    </configSections> 
    <appSettings> 
    <add key="foo" value="BAZ"/> 
    </appSettings> 
    <fooSection> 
    <bar> 
     <add baz2="foo foo"/> 
    </bar> 
    </fooSection> 
</configuration> 

有什么办法能有这个读入核心(或装)配置,就像你将获得机器 - >应用程序配置文件优先? (或甚至machine.config - >机器根目录web.config - >本地应用程序web.config)

在这个例子中,我想config.AppSettings [“foo”]是“BAZ”和fooSection包含两个物品:“foo bar baz”和“foo foo”。

我找不到方法,并且猜测它可能不被支持。我尝试了很多排列组合。

MySection section = ConfigurationManager.GetSection("foo") as MySection; 

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); 
fileMap.LocalUserConfigFilename = // have tried this; 
fileMap.ExeConfigFilename = // have tried this 
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); 
ConfigurationManager.RefreshSection("foo"); 

foo = ConfigurationManager.GetSection("foo") as MySection; 
// will only have one item 
foo = config.GetSection("foo") as MySection; 
// will only have one item 

回答

0

你为什么要这么做?在我看来,你似乎试图处理生产配置?如果是这样的话,那么我会建议看看.config转换。事实上,Scott Hanselman写了一个good post on the subject

否则,我不认为这是可能的。特别是,在配置转换的灵活性。

+0

谢谢,贾斯汀。这在某些情况下可能会有用。现在我运行一个产品的回归测试,并且可以指定-config path \ to.config来测试某些功能,所以对构建理念的改变可能会使这一点适合。 – 2012-03-14 07:05:35

+0

另一种情况是,程序可能不是从本地路径运行,而是从网络共享运行(软件分发比较容易)。假设它是作为控制台应用程序或Windows服务运行的 - 您可以指定命令行选项,或指向为本地主机量身定制的配置文件。 – 2012-03-14 07:07:39

+0

它可能会帮助, 2012-03-27 17:54:04