自訂群組建以處理產生的檔案

在任何指定的組建中,在建置期間產生的檔案的行為與靜態檔案不同 (例如原始程式檔)。 基於這個理由,請務必了解 MSBuild 如何建置專案。 這兩個階段是評估階段執行階段。 在評估階段,MSBuild 會讀取您的專案、匯入所有項目、建立屬性、擴充項目的 Glob,以及設定建置流程。 在執行階段期間,MSBuild 會執行目標與工作,並在評估階段剖析的資料來執行組建。

在評估階段期間產生的檔案不存在,因此不會包含在建置流程中。 若要解決此問題,您必須手動將產生的檔案新增至建置流程。 建議的做法是在 BeforeBuild 目標之前,將新檔案新增至 ContentNone 項目,如下列範例所示:

<Target Name="MyTarget" BeforeTargets="BeforeBuild">
  
  <!-- Some logic that generates your file goes here -->
  <!-- Generated files should be placed in $(IntermediateOutputPath) -->

  <ItemGroup>
    <!-- If your generated file was placed in `obj\` -->
    <None Include="$(IntermediateOutputPath)my-generated-file.xyz" CopyToOutputDirectory="PreserveNewest"/>
    <!-- If you know exactly where that file is going to be, you can hard code the path. -->
    <None Include="some\specific\path\my-generated-file.xyz" CopyToOutputDirectory="PreserveNewest"/>
    
    <!-- If you want to capture "all files of a certain type", you can glob like so. -->
    <None Include="some\specific\path\*.xyz" CopyToOutputDirectory="PreserveNewest"/>
    <None Include="some\specific\path\*.*" CopyToOutputDirectory="PreserveNewest"/>
  </ItemGroup>
</Target>

將產生的檔案新增至 NoneContent 足以讓建置流程查看它。 您也想要確保它會在正確的時間新增。 在理想情況下,您的目標會在 BeforeBuild 之前執行。 AssignTargetPaths 是另一個可能的目標,因為它是在轉換成新項目之前修改 NoneContent 項目 (以及其他項目) 的最後機會。 請參閱一般項目類型