私はいくつかの解決策を試しましたが、これが私が個人的に見つけた最も簡単なものです。
Danはコメントで、元の投稿はOleg Sychのものであると指摘しました—<strong>ありがとう、Oleg!
手順は次のとおりです。
1. 各構成の XML ファイルをプロジェクトに追加します。
通常Debug
、 と の構成があるため、ファイルに とRelease
という名前を付けます。私のプロジェクトでは、環境の種類ごとに構成を作成したので、それを試してみることをお勧めします。App.Debug.config
App.Release.config
2. プロジェクトをアンロードし、.csproj ファイルを開いて編集する
Visual Studio では、.csprojファイルをエディターで直接編集できます。最初にプロジェクトをアンロードするだけで済みます。次に、それを右クリックしてEdit <ProjectName>.csprojを選択します。
3. App.*.config ファイルをメインの App.config にバインドします
すべてApp.config
とApp.*.config
参照を含むプロジェクト ファイル セクションを見つけます。ビルド アクションが次のように設定されていることに気付くでしょうNone
。
<None Include="App.config" />
<None Include="App.Debug.config" />
<None Include="App.Release.config" />
次に、すべての構成固有のファイルをメインに依存App.config
させ、 Visual Studio がデザイナー ファイルやコード ビハインド ファイルと同じようにグループ化するようにします。
上記の XML を以下のものに置き換えます。
<None Include="App.config" />
<None Include="App.Debug.config" >
<DependentUpon>App.config</DependentUpon>
</None>
<None Include="App.Release.config" >
<DependentUpon>App.config</DependentUpon>
</None>
4. 変換マジックを有効にします ( VS2019などの Visual Studio バージョンでは引き続き必要です) 。
後のファイルの最後に
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
そしてファイナル前
</Project>
次の XML を挿入します。適切な変換が行われるには 2 つの手順があることに注意してください。
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="BeforeBuild" Condition="Exists('App.$(Configuration).config')">
<!-- Generate transformed app config and replace it: will get the <runtime> node and assembly bindings properly populated -->
<TransformXml Source="App.config" Destination="App.config" Transform="App.$(Configuration).config" />
</Target>
<Target Name="AfterBuild" Condition="Exists('App.$(Configuration).config')">
<!-- Generate transformed app config in the intermediate directory: this will transform sections such as appSettings -->
<TransformXml Source="App.config" Destination="$(IntermediateOutputPath)$(TargetFileName).config" Transform="App.$(Configuration).config" />
<!-- Force build process to use the transformed configuration file from now on.-->
<ItemGroup>
<AppConfigWithTargetPath Remove="App.config" />
<AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config">
<TargetPath>$(TargetFileName).config</TargetPath>
</AppConfigWithTargetPath>
</ItemGroup>
</Target>
App.config
これで、プロジェクトをリロードしてビルドし、変換を楽しむことができます!
ご参考までに
App.*.config
ファイルが次のように正しく設定されていることを確認してください。
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<!--magic transformations here-->
</configuration>