基于Alex's answer,也许这就是你要找的……
我一直在为 Azure WebJobs 项目寻找一个简单的解决方案,以便在构建期间转换 App.config,该解决方案可与服务器上的 Visual Studio 和 MSBuild 一起使用。
1.将每个配置的 XML 文件添加到项目中。
通常您将拥有Debug 和Release 配置,因此将您的文件命名为App.Debug.config 和App.Release.config。在我的项目中,我为每种环境都创建了一个配置,因此您可能想尝试一下。
2。卸载项目并打开 .csproj 文件进行编辑
Visual Studio 允许您直接在编辑器中编辑 .csproj 文件——您只需先卸载项目。然后右键单击它并选择Edit .csproj。
3.将 App.*.config 文件绑定到主 App.config
找到包含所有App.config 和App.*.config 引用的项目文件部分。您会注意到他们的构建操作设置为None:
<None Include="App.config" />
<None Include="App.Debug.config" />
<None Include="App.Release.config" />
首先,将所有这些的构建操作设置为Content。
接下来,使所有配置特定文件依赖主App.config,以便Visual Studio像设计器和代码隐藏文件一样对它们进行分组。
将上面的 XML 替换为下面的:
<Content Include="App.config" />
<Content Include="App.Debug.config" >
<DependentUpon>App.config</DependentUpon>
</Content>
<Content Include="App.Release.config" >
<DependentUpon>App.config</DependentUpon>
</Content>
4.激活变形魔法
在文件末尾之后
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
在决赛之前
</Project>
插入以下 XML:
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="AfterCompile" Condition="exists('app.$(Configuration).config')">
<!-- Generate transformed app config in the intermediate directory -->
<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 转换!
仅供参考
确保您的 App.*.config 文件具有如下正确设置:
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<!--magic transformations here-->
</configuration>