TExcelTAD
Home › .NET Builds: MSBuild & NuGet › Items, Metadata & Transforms

Items, Metadata & Transforms

Properties hold one string. Items hold lists: the source files to compile, the packages to restore, the files to copy to the output, the projects to reference. Every item has a type (Compile, PackageReference, None…), an identity (usually a path) and any number of metadata values. Most of the SDK is targets that read item lists and produce new ones.

Include, Exclude, Remove

bash · try it yourself
mkdir items && cd items
mkdir -p src/core src/legacy docs
touch src/main.cs src/core/math.cs src/core/math.Tests.cs src/legacy/old.cs docs/guide.md
cat > items.proj <<'XML'
<Project>
  <ItemGroup>
    <Source Include="src/**/*.cs" Exclude="src/**/*.Tests.cs" />
    <Source Remove="src/legacy/**" />
    <Doc Include="docs/*.md;README.md" />
  </ItemGroup>
  <Target Name="Show">
    <Message Importance="high" Text="Source: @(Source)" />
    <Message Importance="high" Text="Count:  @(Source->Count())" />
    <Message Importance="high" Text="Doc:    @(Doc, ' | ')" />
  </Target>
</Project>
XML
dotnet msbuild -nologo -v:m -t:Show
  Source: src/core/math.cs;src/main.cs
  Count:  2
  Doc:    docs/guide.md | README.md
  • @(Source) expands to the list joined with ;. @(Doc, ' | ') picks another separator.
  • ** matches any depth of folders and * any file name. Exclude filters one Include; Remove takes items out of the list afterwards, whatever added them. In SDK projects you almost always use Remove, because Include was done for you by the default globs.
  • README.md doesn't exist, but it's in the list: an Include without wildcards adds the item as written, without checking the disk. Wildcards only match existing files.
  • @(Source->Count()) is an item function. Others: Distinct(), Reverse(), WithMetadataValue('Name', 'value'), AnyHaveMetadataValue(…), DirectoryName().

Metadata

Every file item gets well-known metadata for free (%(Filename), %(Extension), %(RelativeDir), %(RecursiveDir), %(FullPath), %(ModifiedTime)…), and you can attach your own as attributes or child elements:

bash · try it yourself
mkdir meta && cd meta
mkdir -p assets/img assets/fonts
touch assets/img/logo.png assets/img/bg.png assets/fonts/mono.ttf
cat > meta.proj <<'XML'
<Project>
  <ItemDefinitionGroup>
    <Asset>
      <Compress>true</Compress>
    </Asset>
  </ItemDefinitionGroup>
  <ItemGroup>
    <Asset Include="assets/**/*.*" />
    <Asset Update="assets/fonts/*" Compress="false" Kind="font" />
  </ItemGroup>
  <Target Name="Show">
    <Message Importance="high" Text="%(Asset.RecursiveDir)%(Asset.Filename)%(Asset.Extension): compress=%(Asset.Compress) kind=%(Asset.Kind)" />
    <Message Importance="high" Text="Outputs: @(Asset->'out/%(RecursiveDir)%(Filename).gz', ', ')" />
    <Message Importance="high" Text="To compress: @(Asset->WithMetadataValue('Compress', 'true')->'%(Filename)')" />
  </Target>
</Project>
XML
dotnet msbuild -nologo -v:m -t:Show
  fonts/mono.ttf: compress=false kind=font
  img/bg.png: compress=true kind=
  img/logo.png: compress=true kind=
  Outputs: out/fonts/mono.gz, out/img/bg.gz, out/img/logo.gz
  To compress: bg;logo

Four ideas in one example:

  1. ItemDefinitionGroup gives every Asset a default Compress=true.
  2. Update changes metadata of items that already exist, without adding new ones. This is how you tweak items created by the SDK's globs, for example <None Update="appsettings.json" CopyToOutputDirectory="PreserveNewest" />.
  3. Batching: %(Asset.Filename) in a task attribute makes MSBuild run the task once per distinct value. That's why the first Message printed three lines.
  4. Transforms: @(Asset->'out/%(RecursiveDir)%(Filename).gz') maps each item to a new string, one-to-one. Transforms are how targets compute output paths from input paths (.cs → .obj, .md → .html), which you'll need for incremental targets.

The SDK's items in a real project

The same mechanics run every .NET build. PackageReference, ProjectReference, Compile, None, Content, EmbeddedResource and Using are all item types, with metadata such as Version, PrivateAssets or CopyToOutputDirectory. A common real-world use of Update:

bash · try it yourself
mkdir app && cd app
cat > app.csproj <<'XML'
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <None Update="config/*.json" CopyToOutputDirectory="PreserveNewest" />
  </ItemGroup>
</Project>
XML
mkdir config
echo '{ "level": "info" }' > config/logging.json
echo 'notes for humans' > NOTES.txt
echo 'System.Console.WriteLine(System.IO.File.ReadAllText("config/logging.json").Trim());' > Program.cs
dotnet build -nologo -v:q > /dev/null
find bin -path '*/config/*'
ls bin/Debug/net10.0 | grep -c NOTES
cd bin/Debug/net10.0 && dotnet app.dll
bin/Debug/net10.0/config/logging.json
0
{ "level": "info" }

config/logging.json and NOTES.txt were both None items from the default glob. Only the updated one got CopyToOutputDirectory, so only it was copied, keeping its folder (%(RecursiveDir)) under the output directory.

Test yourself

What does <Compile Update="Generated/*.cs" Visible="false" /> do in an SDK project?

  1. Adds the Generated files a second time
  2. Changes metadata on the Compile items that already match, without adding items
  3. Removes the Generated files
  4. Nothing; Update only works on PackageReference

A task attribute contains %(Asset.Kind). What does MSBuild do?

  1. Runs the task once for all items
  2. Runs the task once per distinct Kind value (batching)
  3. Fails: metadata can't be used in tasks
  4. Uses the first item's Kind

@(Doc->'%(Filename).html') on items a.md;b.md produces…

  1. a.md;b.md
  2. a.html;b.html
  3. a.md.html;b.md.html
  4. html