npx skills add ...
npx skills add dotnet/skills --skill msbuild-antipatterns
Detect and fix MSBuild anti-patterns in project and build files. USE WHEN asked to review, audit, lint, clean up, or code-review a .csproj/.vbproj/.fsproj/.props/.targets/.proj (or Directory.Build.props/.targets) file, when asked 'is this project file correct?' or 'what's wrong with my build file?', or when hunting subtle build bugs caused by how a project is authored. Each anti-pattern has a symptom and a concrete BAD→GOOD fix. DO NOT USE FOR: non-MSBuild build systems (npm, Maven, CMake), or migrating a project to SDK-style (use msbuild-modernization).
npx skills add dotnet/skills --skill msbuild-antipatterns
A numbered catalog of common MSBuild anti-patterns. Each entry follows the format:
Use this catalog when scanning project files for improvements.
<Exec> for Operations That Have Built-in TasksSmell: <Exec Command="mkdir ..." />, <Exec Command="copy ..." />, <Exec Command="del ..." />
Why it's bad: Built-in tasks are cross-platform, support incremental build, emit structured logging, and handle errors consistently. <Exec> is opaque to MSBuild.
Built-in task alternatives:
| Shell Command | MSBuild Task |
|---|---|
mkdir | <MakeDir> |
copy / cp | <Copy> |
del / rm | <Delete> |
move / mv | <Move> |
echo text > file | <WriteLinesToFile> |
touch | <Touch> |
xcopy /s | <Copy> with item globs |
Smell: Condition="$(Foo) == Bar" — either side of a comparison is unquoted.
Why it's bad: If the property is empty or contains spaces/special characters, the condition evaluates incorrectly or throws a parse error. MSBuild requires single-quoted strings for reliable comparisons.
Rule: Always quote both sides of == and != comparisons with single quotes.
Smell: Paths like C:\tools\, D:\packages\, /usr/local/bin/ in project files.
Why it's bad: Breaks on other machines, CI environments, and other operating systems. Not relocatable.
Preferred path properties:
| Property | Meaning |
|---|---|
$(MSBuildThisFileDirectory) | Directory of the current .props/.targets file |
$(MSBuildProjectDirectory) | Directory of the .csproj |
$([MSBuild]::GetDirectoryNameOfFileAbove(...)) | Walk up to find a marker file |
$([MSBuild]::NormalizePath(...)) | Combine and normalize path segments |
Smell: Properties set to values that the .NET SDK already provides by default.
Why it's bad: Adds noise, hides intentional overrides, and makes it harder to identify what's actually customized. When defaults change in newer SDKs, the redundant properties may silently pin old behavior.
Smell: <Compile Include="File1.cs" />, <Compile Include="File2.cs" /> in SDK-style projects.
Why it's bad: SDK-style projects automatically glob **/*.cs (and other file types). Explicit listing is redundant, creates merge conflicts, and new files may be accidentally missed if not added to the list.
Exception: Non-SDK-style (legacy) projects require explicit file includes. If migrating, see msbuild-modernization skill.
Exception (F# / .fsproj): F# compilation is order-dependent — the compiler processes <Compile Include> items sequentially and a file can only reference types/modules declared in files listed above it. .fsproj files must therefore list every source file explicitly, in dependency order (utility/leaf modules at the top, the entry point such as Program.fs at the bottom). If a .fsi signature file is used, it must appear immediately before its companion .fs implementation file.
<Reference> with HintPath for NuGet PackagesSmell: <Reference Include="..." HintPath="..\packages\SomePackage\lib\..." />
Why it's bad: This is the legacy packages.config pattern. It doesn't support transitive dependencies, version conflict resolution, or automatic restore. The packages/ folder must be committed or restored separately.
Note: <Reference> without HintPath is still valid for .NET Framework GAC assemblies like WindowsBase, PresentationCore, etc.
PrivateAssets="all" on Analyzer/Tool PackagesSmell: <PackageReference Include="StyleCop.Analyzers" Version="..." /> without PrivateAssets="all".
Why it's bad: Without PrivateAssets="all", analyzer and build-tool packages flow as transitive dependencies to consumers of your library. Consumers get unwanted analyzers or build-time tools they didn't ask for.
See references/private-assets.md for BAD/GOOD examples and the full list of packages that need this.
Smell: The same <PropertyGroup> block appears in 3+ project files.
Why it's bad: Maintenance burden — a change must be made in every file. Inconsistencies creep in over time.
See directory-build-organization skill for full guidance on structuring Directory.Build.props / Directory.Build.targets.
Smell: <PackageReference Include="X" Version="1.2.3" /> with different versions of the same package across projects.
Why it's bad: Version drift — different projects use different versions of the same package, leading to runtime mismatches, unexpected behavior, or diamond dependency conflicts.
Fix: Use Central Package Management. See https://learn.microsoft.com/en-us/nuget/consume-packages/central-package-management for details.
Smell: A single <Target> with 50+ lines doing multiple unrelated things.
Why it's bad: Can't skip individual steps via incremental build, hard to debug, hard to extend, and the target name becomes meaningless.
Inputs and OutputsSmell: <Target Name="MyTarget" BeforeTargets="Build"> with no Inputs / Outputs attributes.
Why it's bad: The target runs on every build, even when nothing changed. This defeats incremental build and slows down no-op builds.
See references/incremental-build-inputs-outputs.md for BAD/GOOD examples and the full pattern including FileWrites registration.
See incremental-build skill for deep guidance on Inputs/Outputs, FileWrites, and up-to-date checks.
Smell: <PropertyGroup> with default values inside a .targets file.
Why it's bad: .targets files are imported late (after project files). By the time they set defaults, other .targets files may have already used the empty/undefined value. .props files are imported early and are the correct place for defaults.
Rule: .props = defaults and settings (evaluated early). .targets = build logic and targets (evaluated late).
Exists() GuardSmell: <Import Project="some-file.props" /> without a Condition="Exists('...')" check.
Why it's bad: If the file doesn't exist (not yet created, wrong path, deleted), the build fails with a confusing error. Optional imports should always be guarded.
Exception — required imports: Imports that are required for the build to work correctly should fail fast — don't guard those. Guard imports that are optional or environment-specific (e.g., local developer overrides, CI-specific settings).
Exception — NuGet package forwarders: .props/.targets files inside a NuGet package's per-TFM build/ or buildTransitive/ folder routinely import a sibling file under buildTransitive/<tfm>/… without an Exists() guard. These are a package contract: the target file is guaranteed to be present in the restored package, even if it doesn't appear in the source tree at that relative path. The package layout is typically produced by:
.nuspec with per-TFM <file> entries — e.g. <file src="buildTransitive\common\MyAdapter.props" target="buildTransitive\net8.0\MyAdapter.props" /> — that copy files from a single source folder (such as buildTransitive/common/) into per-TFM subfolders at pack time, or<None Update="..."> / <Content Include="..."> items in the .csproj with a per-TFM <PackagePath> (e.g. <PackagePath>buildTransitive/net8.0/</PackagePath>), declared once per target TFM, orIncludeBuildOutput, BuildOutputTargetFolder) that place built outputs under build/<tfm>/.Before flagging an unguarded <Import> inside a build/ or buildTransitive/ folder, resolve it against the packed layout — read every *.nuspec in the project directory and its immediate parent directory (shared nuspecs are common in mono-repos; do not walk further up), and any <PackagePath> metadata on <None>/<Content> items in the .csproj. Only flag if the target path is missing from both the source tree and the projected package layout. The dotnet-msbuild/extension-points skill — Source tree vs packed layout — documents the full cross-check procedure.
Forwarding buildTransitive/ → build/: forward through the sibling build/*.props / build/*.targets file (not directly to buildMultiTargeting/); when build/ is per-TFM (build/<tfm>/), include the TFM segment derived from the file's own folder (not $(TargetFramework)), or transitive consumers hit MSB4019. See the extension-points skill — Forwarding chain — for the rule and derivation expression.
Smell: Backslash path separators in .props/.targets files meant to run cross-platform.
Where this is a real bug (🔴 Error) — paths that MSBuild does not route through its path normalizer:
<Exec Command="...\tools\foo.exe ..." /> — passed verbatim to bash/sh on Unix, which treats \ as an escape.<WriteLinesToFile>, or constructed for non-MSBuild consumers (custom scripts, response files, environment variables).Where this is only a style preference (🔵 Style) — paths that go through MSBuild's evaluator (<Import Project="...">, file-path properties consumed by built-in tasks like <Copy>/<MakeDir>/<Delete>, item Include=/Exclude= globs):
MSBuild's evaluator normalizes \ → / on Unix-like systems before resolving the path. See FileUtilities.MaybeAdjustFilePath and ConvertToUnixSlashes in microsoft/msbuild src/Framework/FileUtilities.cs. So <Import Project="$(MSBuildThisFileDirectory)..\..\build\common.props" /> resolves correctly on Linux/macOS today. Forward slashes are still preferred for consistency, but the import will not break and existing backslash-style imports should not be flagged as 🔴 Error.
Verification rule: Before flagging a backslash path as 🔴 Error, ask "does this string flow through MSBuild's evaluator, or is it handed verbatim to a non-MSBuild consumer?" Only the second case is a correctness defect.
Note: $(MSBuildThisFileDirectory) already ends with a platform-appropriate separator, so $(MSBuildThisFileDirectory)tools/mytool works on both platforms.
Smell: A property set unconditionally in both Directory.Build.props and a .csproj — last write wins silently.
Why it's bad: Hard to trace which value is actually used. Makes the build fragile and confusing for anyone reading the project files.
For additional anti-patterns (AP-16 through AP-23) and a quick-reference checklist, see additional-antipatterns.md.**