---
# System prepended metadata

title: 'VS2022 中, 覆寫<target Name="Build"> 無效怎麼辦?'
tags: [SDK-Style, VS2022, MSBuild 17]

---

# VS2022 中, 覆寫<target Name="Build"> 無效怎麼辦?


最近開發一個C# Winform 小程式, 想要建置程式前, 自動在建置目錄增加logs檔, 以便在測試階段, 測試log功能是否正常.

###### tags: `VS2022` `MSBuild 17` `SDK-Style`


## 作法:
### 1. 用notepad++開啟csprj檔案, 簡單情況如下:
```xml=
<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net6.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <UseWindowsForms>true</UseWindowsForms>
    <ImplicitUsings>enable</ImplicitUsings>

	<AssemblyName>LittleForm</AssemblyName>
    <OutputPath>bin\</OutputPath>
  </PropertyGroup>
  ...
</Project>
```
### 2. 增加下列片段到<Project> tag 之下
```xml=
<target Name="t1" BeforeTargets="Build">
    <MakeDir Directory="bin\$(TargetFramework\logs\)" />
</target>
```
### 3. 整合後的csproj檔
```xml=
<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net6.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <UseWindowsForms>true</UseWindowsForms>
    <ImplicitUsings>enable</ImplicitUsings>

	<AssemblyName>LittleForm</AssemblyName>
    <OutputPath>bin\</OutputPath>
  </PropertyGroup>
  <target Name="t1" BeforeTargets="Build">
    <MakeDir Directory="bin\$(TargetFramework\logs\)" />
  </target>
</Project>
```

參考[這篇](https://docs.microsoft.com/en-us/visualstudio/msbuild/how-to-extend-the-visual-studio-build-process?view=vs-2022),花了很多時間測試以下語法, 結果MSBuild 都沒有做出相應的動作
```xml=
<target Name="Build">
    <MakeDir Directories="$(OutputDir)" />
</target>
```

才知道 sdk style 會讓自訂的<Target Name="Build"></Target> 失效.:cry::cry::cry:

原因是sdk style 是.net 5以後提供的一個省code的style。MSBuild 看到這個style,會在解譯csproj檔案之後插入語法, 所以自訂的<Target Name="Build"></Target>會失效. 
![](https://i.imgur.com/9mELS1X.png)

    
希望這篇文章可以節省大家的時間。

## 參考資料:
1. [MSDoc](https://docs.microsoft.com/en-us/visualstudio/msbuild/how-to-extend-the-visual-studio-build-process?view=vs-2022)
2. [MSBuild 入門(CSProj檔)](https://www.syscom.com.tw/ePaper_Content_EPArticledetail.aspx?id=136&EP.)
3. [MakeDir 類似Task Reference](https://docs.microsoft.com/en-us/visualstudio/msbuild/makedir-task?view=vs-2022)
4. [從 .net 5 開始，Windows Forms 和 Windows Presentation Foundation (WPF) 專案應指定 .net SDK](https://docs.microsoft.com/zh-tw/dotnet/core/project-sdk/overview)

    