我也遇到过类似的问题。这就是我所做的:
我的 app.config 如下所示:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="ConenctToInputDB" value="InputDev" />
<add key="ConnectToOutputDB" value ="OutputDev"/>
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
<connectionStrings>
<add name="LocalConnection" connectionString="YOUR CONNECTION STRING HERE" />
<add name="InputDev" connectionString="YOUR CONNECTION STRING HERE" />
<add name="InputCert" connectionString="YOUR CONNECTION STRING HERE"/>
<add name="OutputDev" connectionString="YOUR CONNECTION STRING HERE/>
<add name="OutputCert" connectionString="YOUR CONNECTION STRING HERE" />
<add name="InputProd" connectionString="YOUR CONNECTION STRING HERE/>
<add name="OutputProd" connectionString="YOUR CONNECTION STRING HERE" />
</connectionStrings>
在这种情况下,我连接了 2 个数据库,每个数据库都有 3 个不同的连接字符串(开发、认证和生产)
将此添加到项目文件的底部(右键单击项目并卸载它)。确保在 </project> 标记之前添加它。 (您需要安装 MSBuild 社区任务才能使其工作。它们可以从以下位置免费下载:http://msbuildtasks.tigris.org/(确保您获得了每晚构建))
<PropertyGroup>
<!--Import the MSBuild community tasks so we can update xml-->
<MSBuildCommunityTasksPath>C:\PathToMSBuildCommunityTasks\MSBuildTasks</MSBuildCommunityTasksPath>
<SubstitutionsFile Condition="'$(Configuration)' == 'Debug'">DevAppSettings.xml</SubstitutionsFile>
<SubstitutionsFile Condition="'$(Configuration)' == 'Cert'">CertAppSettings.xml</SubstitutionsFile>
<SubstitutionsFile Condition="'$(Configuration)' == 'Prod'">ProdAppSettings.xml</SubstitutionsFile>
</PropertyGroup>
<Import Project="C:\PathToMSBuildCommunityTasks\lib\MSBuildTasks\MSBuild.Community.Tasks.Targets" />
<Target Name="AfterBuild">
<!--Update the app config to have the correct environment paths-->
<Message Text="Updating $(MSBuildProjectName) config to $(Configuration)" Importance="high"></Message>
<XmlMassUpdate ContentFile="$(OutDir)\$(MSBuildProjectName).dll.config" SubstitutionsFile="..\..\$(SubstitutionsFile)" />
</Target>
这将根据当前配置替换 app.config 文件的 <appSettings> 部分。您将需要进行新的配置(我称它们为 Cert 和 Prod)。
最后一步是为每个配置创建一个文件(我称它们为 DevAppConfig.xml、CertAppConfig.xml、ProdAppConfig.xml)
在每个文件中应该是这样的(这个是用于认证配置的):
<?xml version="1.0" encoding="utf-8"?>
<!--This file is used by the build files to merge in solution wide app settings
Some projects contain files that have an AppSetting section (usually in App.config). Those projects have
and AfterBuild event in the project file that substitues this xml tree over the the normal xml tree.-->
<configuration xmlns:xmu="urn:msbuildcommunitytasks-xmlmassupdate">
<appSettings>
<add xmu:key="key" key="ConenctToInputDB" value="Cert"/>
<add xmu:key="key" key="ConnectToOutputDB" value="ESPCert"/>
</appSettings>
</configuration>
所有这些,一旦安装,app.config 输出的文件将根据您正在编译的配置自动更改。此代码适用于在 IDE 和 Team Build 中进行编译。