---
# System prepended metadata

title: 'Visual Studio App.config, Nlog.config 編編時根據環境參數自動轉換'
tags: [工具使用]

---

---
tags: 工具使用
---
# Visual Studio App.config, Nlog.config 編編時根據環境參數自動轉換

當我們想要在編編的時候, Visual Studio 能跟自動據環境參數 Debug, Release 等等, 去自動Build 不同設定內容的 App.config, NLog.config 或者其他的設定檔都可以。
Project 一開始的時候可能只有 App.config, Nlog.config, 自己複製出 Release, Debug 等 Config 版本, 然後修改Project檔案(.csproj), 
修改成這段內容
```xml=
  <ItemGroup>
    <None Include="App.config" />
    <None Include="App.Release.config">
      <DependentUpon>App.config</DependentUpon>
    </None>
    <None Include="NLog.config" />
    <None Include="NLog.Release.config">
      <DependentUpon>NLog.config</DependentUpon>
    </None>
    <None Include="NLog.Debug.config">
      <DependentUpon>NLog.config</DependentUpon>
    </None>
  </ItemGroup>
```
新增這段在最後
```xml=
  <UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
  <Target Name="AfterCompile" Condition="Exists('App.$(Configuration).config')">
    <TransformXml Source="App.config" Destination="$(IntermediateOutputPath)$(TargetFileName).config" Transform="App.$(Configuration).config" />
    <ItemGroup>
      <AppConfigWithTargetPath Remove="@(AppConfigWithTargetPath)" />
      <AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config">
        <TargetPath>$(TargetFileName).config</TargetPath>
      </AppConfigWithTargetPath>
    </ItemGroup>
  </Target>
  <UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
  <Target Name="AfterCompile">
    <TransformXml Source="NLog.config" Destination="$(OutputPath)\NLog.config" Transform="NLog.$(Configuration).config" />
  </Target>
```

[設定1參考](https://dotblogs.com.tw/supershowwei/2022/12/19/manually-add-configuration-transform-for-windows-form-application)

[設定2參考](https://stackoverflow.com/questions/53504590/invalid-value-for-the-configfile-paramter-of-the-generationapplication-manifest)

[MS Build 設定參考](https://johan.driessen.se/posts/Applying-MSBuild-Config-Transformations-to-any-config-file-without-using-any-Visual-Studio-extensions/)

[設定檔內容轉換參考](https://learn.microsoft.com/en-us/previous-versions/aspnet/dd465326(v=vs.110))

也可以用 [Configuration Transform](https://marketplace.visualstudio.com/items?itemName=GolanAvraham.ConfigurationTransform)擴展