[Console Application]讓 WinForm、Console Application 的 App.config 也有 Debug 和 Release 自動置換的功能(進階版)

  • 1566
  • 0
  • 2016-05-11

摘要:[Console Application] 讓 WinForm、Console Application 的 App.config 也有 Debug 和 Release 自動置換的功能(進階版)

說明與感謝

 

今天主題為嘗試實作 亂馬客大大 所發表 "[.NET]transform app.config" 文章,並隨手紀錄一下,其嘗試的過程。 能有這一篇文章首先必須感謝 亂馬客大大 及 相關作者 ,感謝您,接下來內容則是過程。

 

 

 

實作環境: Visual Studio 2013

 

步驟1.

 

開啟一個 新ConsoleApplication專案 並命名為 ConsoleApplicationTest。

 

 

步驟2.

 

下文XML程式碼 複製兩份到專案內,並且分別命名為 App.Debug.config 、 App.Release.config


<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
</configuration>

 

 

步驟3.

 

[ConsoleApplicationTest] 按右鍵,選取 [卸除專案] (圖3.1)後, 對 [ConsoleApplicationTest] 按右鍵,選取 [編輯ConsoleApplicationTest.csprojt]

 

下圖3.1

 

下圖3.2

 

 

步驟4.

 

在 ConsoleApplicationTest.csprojt 中,找到下面XML程式碼段落


  <ItemGroup>
    <None Include="App.config" />
  </ItemGroup>

,在該段落(<ItemGroup>)中 <None Include="App.config" /> 下一行緊接著插入,下面XML程式碼段落


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

 

結果如下圖

 

 

步驟5.

 

</Project> 標籤前一行插入下面XML程式碼 (XML程式碼來源: https://gist.github.com/tathamoddie/5873372)


  <PropertyGroup>
    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
    <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
  </PropertyGroup>
  <UsingTask TaskName="TransformXml" AssemblyFile="$(VSToolsPath)\Web\Microsoft.Web.Publishing.Tasks.dll" />
  <Target Name="AfterCompile" Condition="exists('app.$(Configuration).config')">
    <!-- Generate transformed app config in the intermediate directory -->
    <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>

 

結果如下圖

 

 

步驟6.

 

儲存 ConsoleApplicationTest.csprojt 檔案,並對 [ConsoleApplicationTest] 按右鍵,
選取 [重新載入專案] (圖6.1)後,並在之後按下相關確認訊息,
即可完成所有設定(圖6.2)。

 

下圖6.1

下圖6.2

 

 

主要參考:

[.NET]transform app.config by 亂馬客
https://gist.github.com/tathamoddie/5873372

 

 

※在此感謝所有的幫助者,感謝~