34
40

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

App.configをビルドターゲットによって書き換える

Last updated at Posted at 2017-02-20

概要

Web.configだとデフォルトで対応していますが、コンソールアプリの場合などは、.csprojectを書き換えたりしないといけません。

ビルドターゲットに応じたファイルを作成する。

App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="setting1" value="settingvalue"/>
    <add key="setting2" value="settingvalue"/>
  </appSettings>
</configuration>
App.Debug.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform" />
App.Release.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <appSettings>
    <add key="setting1" value="settingvalue-release" xdt:Transform="Replace" xdt:Locator="Match(key)"/>
  </appSettings>
</configuration>

.csprojectファイルを編集する

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

これを、下記の通り変更する。

project.csproject
  <ItemGroup>
    <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>
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

の下に、下記を追加

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

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
40

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?