VS2012で、App.configを環境別にApp.Debug.config/App.Release.configで更新する

Web.configの環境切り替え(Web.Debug.config/Web.Release.config)と同じことを、コンソールアプリケーションやWindowアプリケーションで行う方法のメモです。

色々なやり方がありましたが、簡単だった上記ページの方式を使いました。
手順は以下の通り。


1.プロジェクトにApp.Debug.configとApp.Release.configを追加する

  • App.Release.Configの中身の例。Web.Release.configの設定方法と同様
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <appSettings>
    <add key="キー名" value="置き換える値"  xdt:Transform="Replace" xdt:Locator="Match(key)"/>
  </appSettings>
</configuration>
  • App.Debug.Configの中身の例(App.configと差し替える項目が無ければ以下の通り)
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
</configuration>

個人的にはApp.Debug.Configは無くても大丈夫です。

2.プロジェクトファイル( .csproj)をテキストエディタで開く


3.プロジェクトファイルのItemGroupの中を直す

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

<Content Include="App.config" />
<Content Include="App.Debug.config" >
  <DependentUpon>App.config</DependentUpon>
  <SubType>Designer</SubType>
</Content>
<Content Include="App.Release.config" >
  <DependentUpon>App.config</DependentUpon>
  <SubType>Designer</SubType>
</Content>

に直す


4.プロジェクトファイルにTargetを追加する
の下で、の前に以下を入れる

<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v11.0\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="app.config" />
    <AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config">
      <TargetPath>$(TargetFileName).config</TargetPath>
    </AppConfigWithTargetPath>
  </ItemGroup>
</Target>

VS2012なのでv10.0ではなく、v11.0にしています


5.ビルドするDebugビルドすればApp.debug.configの内容で差分更新され、ReleaseビルドすればApp.release.configの内容で差分更新されました。

TFSやJenkinsなどのCIサーバーでデプロイする場合は、VSのApp.Release.configの中身は空でも良いかもしれません。CIサーバーのデプロイ時に本当のApp.Releaase.Configで上書きするほうが、間違って本番につないでしまう可能性がないので安全だと思います。