C#のアプリケーションでは設定情報を格納しておくためのファイルとして「App.Config」がありますが、開発時点ではテスト用の設定情報を利用したい場合もあります。
Debugビルドの時とReleaseビルドの時で App.Config を使い分けることができれば便利ですね。
Debug用とRelease用のApp.Configを準備する
Debugビルドの時に使用するファイルとして「App.Debug.config」を、
Releaseビルドの時に使用するファイルとして「App.Release.config」をそれぞれ作成します。
全てのビルドで共通する設定は「App.Config」へ記述し、
Debugビルド時に専用の値にしたい設定は「App.Debug.Config」へ
Releaseビルド時に専用の値にしたい設定は「App.Release.Config」へ記述するという感じです。
以下のようなサンプルのApp.Configで解説します。
「TestKey1」と「TestKey2」というキーがありますが、このうち「TestKey2」の値をDebugとReleaseで別々の値にするという使い方の例になります。
App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8.1" />
</startup>
<appSettings>
<add key="TestKey1" value="KEY1です!" />
<add key="TestKey2" value="KEY2です!" />
</appSettings>
</configuration>
App.Debug.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add key="TestKey2" value="KEY2です!(debug)" xdt:Transform="Replace" xdt:Locator="Match(key)" />
</appSettings>
</configuration>
App.Release.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add key="TestKey2" value="KEY2です!(release)" xdt:Transform="Replace" xdt:Locator="Match(key)" />
</appSettings>
</configuration>
「App.Debug.Config」と「App.Release.Config」には <configuration> タグに
xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform" という属性を追加します。
また <add>タグにも xdt:Transform="Replace" xdt:Locator="Match(key)" という属性を追加します。
App.Debug.ConfigとApp.Release.Configプロジェクトへ追加
作成した「App.Debug.Config」と「App.Release.Config」の2つのファイルをプロジェクトに追加しましょう。
ただ普通に追加すると App.Config と並列に並んでしまいますね。
App.Config のサブ階層になるようにするためにプロジェクトファイル(.csproj)を編集しましょう。
下記のような部分を探して・・・
[アプリ名].csproj ※編集前
<None Include="App.Debug.config" />
<None Include="App.Release.config" />
こんな感じに書き換えます。
[アプリ名].csproj ※編集後
<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>


コメント
コメントを投稿