C# 如何在 MsBuild 加上自訂選項或流程

Ryan Hsu
Ryan Hsu
Aug 25, 2017 · 3 min read

情境

當同一份 C# .NET 的 Source Code 可以依照 solution file build 出不同的版本,因為有不同的 solution 檔案,通常也會有不同的 csproj 檔案。

而如果有某個自訂的目標(PropertyGroup, ItemGroup…)有可能經常修改,那每次修改就要逐個 csproj 檔案都要修改,這十分的麻煩,萬一維護的人沒改到就慘了!

解法

Step.1

抽出自訂方法為一個 MyTasks 資料夾與 solution 同一層,依照自訂內容不同命名與改寫。

MyProject

├─Libary1
├─Libary2
├─MyWebSite
│ ├─bin
│ ├─csproj1
│ ├─csproj2
│ ├─csproj3
│ └─csproj4
├─CustomTasks
│ ├─MyTask1.config
│ └─MyTask2.config
├─solution1
├─solution2
├─solution3
└─solution4

Step.2

寫自訂 Task 檔案

<?xml version="1.0" encoding="utf-8"?><Project ToolsVersion=<version number>  DefaultTargets="TargetC;TargetD"  xmlns="http://schemas.microsoft.com/developer/msbuild/2003">// your Task here.</Project>

Step.3

在各個 csproj 裡面 import 設定檔案

<?xml version="1.0" encoding="utf-8"?><Project InitialTargets="TargetA;TargetB"  
DefaultTargets="TargetC;TargetD"
TreatAsLocalProperty="PropertyA;PropertyB"
ToolsVersion=<version number>
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

<Import Project="..\CustomTasks\MyTask1.config" >
<Import Project="..\CustomTasks\MyTask2.config" >
</Project>

以上

記錄一下,這樣就可以囉!

)
Ryan Hsu

Written by

Ryan Hsu

Front-end developer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade