在參考某個開源專案 .csproj 看到類似 <PostBuildEvent>copy $(TargetDir)Blah.dll D:\</PostBuildEvent> 發現它會被觸發,但 $(TargetDir) 抓不到輸出路徑而是空值。

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <PostBuildEvent>COPY $(TargetDir)Blah.dll D:\</PostBuildEvent>
  </PropertyGroup>

</Project>

爬文發現是個已知問題,PreBuildEvent/PostBuildEvent 在 .NET Core/.NET 6+ 預計會停用 (但還沒停用會被執行,只是變數功能失效),建議改用 <Target Name="PostBuild" AfterTargets="PostBuildEvent">。以下是對照測試:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <!-- 舊寫法 -->
    <PostBuildEvent>echo PostBuildEvent Element - $(TargetDir)</PostBuildEvent>
  </PropertyGroup>
  <!-- 建議寫法 -->
  <Target Name="PostBuild" AfterTargets="PostBuildEvent">
    <Exec Command="echo Target Element - $(TargetDir)" />
  </Target>

</Project>

如上圖,新舊寫法都有執行,但舊寫法找不到 $(TargetDir)。

Issue of PreBuildEvent and PostBuildEvent failed to read build variables (ex: $(TargetDir)).


Comments

Be the first to post a comment

Post a comment