如何使用 Visual Studio 在线和 .NET 桌面应用程序进行文件转换/变量替换

How to do file transforms / variable substitution with Visual Studio Online and .NET Desktop App

Visual Studio Team Services Online (www.visualstudio.com) 发布定义在 IIS Web App Deploy 中有一个设置来执行 XML 变量替换。基于在线帮助:

Variables defined in the Build or Release Definition will be matched against the 'key' or 'name' entries in the appSettings, applicationSettings, and connectionStrings sections of any config file and parameters.xml. Variable Substitution is run after config transforms.

在部署 .NET 面向桌面的版本(用于桌面应用程序或 Windows 服务)时,是否有任何此类 简单 任务可以应用?具体来说,我想替换 appSettings.config 文件的键值元素的 value 部分(或者,post-build 它们现在是 *.exe.config)。

我见过一些代币替代市场附加组件,但这些都不起作用。它们将替换 appSetting 的 value 部分,但不基于 key。我可能可以用鞋拔它,但它既不优雅又脆弱。

您可以添加这两个 vsts 扩展来完成这项工作。

https://marketplace.visualstudio.com/items?itemName=qetza.xdttransform

https://marketplace.visualstudio.com/items?itemName=ms-devlabs.utilitytasks 从这一秒开始你想使用分词器任务。

它们都有很好的文档记录,因此您可以实施它。

根据@Rodrigo-werlang的回答,这里有一个更完整的解决方案:

1) 创建XDT 转换文件。我遵循了一个让我编辑 .csproj 文件以创建 app.debug.config 等的线程,但最终不需要这样做。我将文件创建为 Release.config,并使用 web.release.config 文件作为转换的基础。

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <appSettings>
    <add key="MagicKey" value="#{MagicKey}#" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
  </appSettings>
</configuration>

2) 在 Release 定义中,为 XDT Transformation 添加一个 Task。将 Release.config 设置应用于右侧 .exe.config 文件。 注意工作文件夹 - 它默认为源代码目录,我想应用到构建工件文件夹。

3) 添加标记化任务。我使用了 Guillaume Rouchon 的 Replace Tokens,但我怀疑任何分词器都可以正常工作。再次记下工作目录。

4) 按照正常设置发布变量。