Example of using Target file in C# project

What is target file ?

projects use .target files to define which files should be imported into the project during the build process (more info).

 

How to use it ?

1.in order to use target files firstly you need to tell your Visual C# project to use this future by adding below line to the project file (.csproj).

<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

2.Then you need to import the targetFile address as below

my target file name is “TargetFileApp.csproj.targets“

3.In the next step you will ask the compiler when to do the target files task

<Target Name="AfterBuild">
  <CallTarget Targets="CopyPackageContent" />
</Target>

A target never build twice but you can order the build by using BeforeTargets and AfterTargets (read more) .

by above line it goes to my target file and looking for “CopyPackageContent” element.

4.now you can add the your desirable tasks to your target file

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
   <TestBase Include="Test\*.*" Exclude="Test\*.etc" />
  </ItemGroup>
  <Target Name="CopyPackageContent">
  <Copy SourceFiles="@(TestBase)" DestinationFiles="@(TestBase-&gt;'$(OutDir)%(RecursiveDir)%(Filename)%(Extension)')" />
    <Warning Text="Content copied from package TestBase.Base to the output folder. Cleaning the project/solution will not delete these files." />
    </Target>
</Project>

In the ItemsGroup you can define your addresses and filter them with Exclude attribute . for instance in this case, it is looking for all the files which exist in Test folder except the one has .etc extension.

when the project is build the compiler find the “CopypackageContent” element in the target file and then start copying from pre defined addresses to destination address (more info about copy task) .

download the whole source of TargetFileApp from my GitHub.

added : I also make a simple application to generate the target file for CSharp project.

posted @   MaxBruce  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
历史上的今天:
2022-01-14 ASP.NET Core on K8S学习初探(3)部署API到K8S
2022-01-14 EF Core导航属性
2021-01-14 C# Task详解
2021-01-14 await 关键字 后面跟Task 和Task <T>
点击右上角即可分享
微信分享提示