VS非web项目使用Transformation配置文件

时间:2023-03-09 07:49:29
VS非web项目使用Transformation配置文件

Web项目中的Transformation使用起来非常方便,特别是本地与服务器情况不一致时调试下以及webdeploy的配合使用。

步骤:

1. 在项目中新建App.Debug.Config及App.Realse.Config文件

    VS非web项目使用Transformation配置文件

粘贴以下代码到新建的Config文件中

<?xml version="1.0" encoding="utf-8"?>

<!-- 有关使用 web.config 转换的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=125889 -->

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<!--
在下例中,“SetAttributes”转换将更改
“connectionString”的值,以仅在“Match”定位器
找到值为“MyDB”的特性“name”时使用“ReleaseSQLServer”。 <connectionStrings>
<add name="MyDB"
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
-->
<system.web>
<!-- 在下例中,“Replace”转换将替换
web.config 文件的整个 <customErrors> 节。
请注意,由于
在 <system.web> 节点下仅有一个 customErrors 节,因此不需要使用“xdt:Locator”特性。 <customErrors defaultRedirect="GenericError.htm"
mode="RemoteOnly" xdt:Transform="Replace">
<error statusCode="500" redirect="InternalError.htm"/>
</customErrors>
-->
</system.web>
</configuration>

2. 右键项目→卸载项目,再次右键项目→编辑项目

    VS非web项目使用Transformation配置文件

    VS非web项目使用Transformation配置文件

3. 在XML中找到最后一个ProjectGroup节点,粘贴以下代码

<PropertyGroup>
  <ProjectConfigFileName>App.config</ProjectConfigFileName>
</PropertyGroup>

    VS非web项目使用Transformation配置文件

4. 找到ItemGroup节点,找到以下代码

  <ItemGroup>
<None Include="App.config" />
</ItemGroup>

替换为

  <ItemGroup>
<None Include="App.config" />
<None Include="App.Debug.config">
<DependentUpon>App.config</DependentUpon>
</None>
<None Include="App.Release.config">
<DependentUpon>App.config</DependentUpon>
</None>
</ItemGroup>

    VS非web项目使用Transformation配置文件

    VS非web项目使用Transformation配置文件

5. 找到以下节点(一般在最下方)

<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

在下方增加以下内容

  <Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets" />
<Target Name="AfterBuild">
<TransformXml Source="@(AppConfigWithTargetPath)" Transform="$(ProjectConfigTransformFileName)" Destination="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')" />
</Target>

6. 保存,重新载入项目,查看效果

    VS非web项目使用Transformation配置文件