我尝试了几种解决方案,这是我个人发现的最简单的解决方案。
Dan在评论中指出原帖属于奥列格·赛奇—谢谢,奥列格!
以下是说明:
1. 将每个配置的 XML 文件添加到项目中。
通常你会有Debug
and Release
配置所以命名你的文件App.Debug.config
and App.Release.config
。在我的项目中,我为每种环境创建了一个配置,因此您可能想尝试一下。
2.卸载项目并打开.csproj文件进行编辑
Visual Studio 允许您编辑.csproj文件就在编辑器中 - 您只需先卸载项目即可。然后右键单击它并选择编辑 .csproj.
3. 将App.*.config文件绑定到主App.config
找到包含所有内容的项目文件部分App.config
and App.*.config
参考。您会注意到他们的构建操作设置为None
没关系:
<None Include="App.config" />
<None Include="App.Debug.config" />
<None Include="App.Release.config" />
接下来,将所有特定配置 files 依赖的在主要的App.config
因此 Visual Studio 将它们分组,就像它对设计器和代码隐藏文件一样。
将上面的 XML 替换为下面的 XML:
<None Include="App.config" />
<None Include="App.Debug.config" >
<DependentUpon>App.config</DependentUpon>
</None>
<None Include="App.Release.config" >
<DependentUpon>App.config</DependentUpon>
</None>
4.激活变形魔法(对于 Visual Studio 版本仍然需要,例如VS2019)
在文件末尾之后
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
并在决赛之前
</Project>
插入以下 XML - 请注意要进行正确的转换需要两个步骤:
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="BeforeBuild" Condition="Exists('App.$(Configuration).config')">
<!-- Generate transformed app config and replace it: will get the <runtime> node and assembly bindings properly populated -->
<TransformXml Source="App.config" Destination="App.config" Transform="App.$(Configuration).config" />
</Target>
<Target Name="AfterBuild" Condition="Exists('App.$(Configuration).config')">
<!-- Generate transformed app config in the intermediate directory: this will transform sections such as appSettings -->
<TransformXml Source="App.config" Destination="$(IntermediateOutputPath)$(TargetFileName).config" Transform="App.$(Configuration).config" />
<!-- Force build process to use the transformed configuration file from now on.-->
<ItemGroup>
<AppConfigWithTargetPath Remove="App.config" />
<AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config">
<TargetPath>$(TargetFileName).config</TargetPath>
</AppConfigWithTargetPath>
</ItemGroup>
</Target>
现在您可以重新加载项目,构建它并享受App.config
转变!
FYI
确保您的App.*.config
文件有这样的正确设置:
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<!--magic transformations here-->
</configuration>