Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

MSBuild reference for .NET SDK projects

  • 2024-11-07
Feedback

In this article

This page is a reference for the MSBuild properties and items that you can use to configure .NET projects.

Note

This page is a work in progress and does not list all of the useful MSBuild properties for the .NET SDK. For a list of common MSBuild properties, seeCommon MSBuild properties.

Assembly validation properties

These properties and items are passed to theValidateAssemblies task. For more information about assembly validation, seeAssembly validation.

The following MSBuild properties are documented in this section:

Note

These properties aren't part of the .NET SDK (yet). To use them, you must also add aPackageReference toMicrosoft.DotNet.ApiCompat.Task.

In addition, the following properties that are documented in thePackage validation properties also apply to assembly validation:

ApiCompatStrictMode

When set totrue, theApiCompatStrictMode property specifies that API compatibility checks should be performed instrict mode.

<PropertyGroup>  <ApiCompatStrictMode>true</ApiCompatStrictMode></PropertyGroup>

ApiCompatValidateAssemblies

TheApiCompatValidateAssemblies property enables a series of validations on the specified assemblies. For more information, seeAssembly validation.

<PropertyGroup>  <ApiCompatValidateAssemblies>true</ApiCompatValidateAssemblies></PropertyGroup>

Assembly attribute properties

GenerateAssemblyInfo

TheGenerateAssemblyInfo property controlsAssemblyInfo attribute generation for the project. The default value istrue. Usefalse to disable generation of the file:

<PropertyGroup>  <GenerateAssemblyInfo>false</GenerateAssemblyInfo></PropertyGroup>

TheGeneratedAssemblyInfoFile setting controls the name of the generated file.

When theGenerateAssemblyInfo value istrue,package-related project properties are transformed into assembly attributes.

For more information about generating assembly attributes using a project file, seeSet assembly attributes in a project file.

GeneratedAssemblyInfoFile

TheGeneratedAssemblyInfoFile property defines the relative or absolute path of the generated assembly info file. Defaults to a file named[project-name].AssemblyInfo.[cs|vb] in the$(IntermediateOutputPath) (usually theobj) directory.

<PropertyGroup>  <GeneratedAssemblyInfoFile>assemblyinfo.cs</GeneratedAssemblyInfoFile></PropertyGroup>

Framework properties

The following MSBuild properties are documented in this section:

TargetFramework

TheTargetFramework property specifies the target framework version for the app. For a list of valid target framework monikers, seeTarget frameworks in SDK-style projects.

<PropertyGroup>  <TargetFramework>net8.0</TargetFramework></PropertyGroup>

For more information, seeTarget frameworks in SDK-style projects.

TargetFrameworks

Use theTargetFrameworks property when you want your app to target multiple platforms. For a list of valid target framework monikers, seeTarget frameworks in SDK-style projects.

Note

This property is ignored ifTargetFramework (singular) is specified.

<PropertyGroup>  <TargetFrameworks>net8.0;net462</TargetFrameworks></PropertyGroup>

For more information, seeTarget frameworks in SDK-style projects.

NetStandardImplicitPackageVersion

Note

This property only applies to projects usingnetstandard1.x. It doesn't apply to projects that usenetstandard2.x.

Use theNetStandardImplicitPackageVersion property when you want to specify a framework version that's lower than the metapackage version. The project file in the following example targetsnetstandard1.3 but uses the 1.6.0 version ofNETStandard.Library.

<PropertyGroup>  <TargetFramework>netstandard1.3</TargetFramework>  <NetStandardImplicitPackageVersion>1.6.0</NetStandardImplicitPackageVersion></PropertyGroup>

Package properties

Descriptive properties

You can specify properties such asPackageId,PackageVersion,PackageIcon,Title, andDescription to describe the package that gets created from your project. For information about these and other properties, seepack target.

<PropertyGroup>  ...  <PackageId>ClassLibDotNetStandard</PackageId>  <Version>1.0.0</Version>  <Authors>John Doe</Authors>  <Company>Contoso</Company></PropertyGroup>

PackRelease

ThePackRelease property is similar to thePublishRelease property, except that it changes the default behavior ofdotnet pack. This property was introduced in .NET 7.

<PropertyGroup>  <PackRelease>true</PackRelease></PropertyGroup>

Note

  • Starting in the .NET 8 SDK,PackRelease defaults totrue. For more information, see'dotnet pack' uses Release configuration.
  • .NET 7 SDK only: To usePackRelease in a project that's part of a Visual Studio solution, you must set the environment variableDOTNET_CLI_ENABLE_PACK_RELEASE_FOR_SOLUTIONS totrue (or any other value). For solutions that have many projects, setting this variable increases the time required to pack.

Package validation properties

These properties and items are passed to theValidatePackage task. For more information about package validation, seePackage validation overview.

For properties for theValidateAssemblies task, seeAssembly validation properties.

The following MSBuild properties and items are documented in this section:

ApiCompatEnableRuleAttributesMustMatch

When set totrue, theApiCompatEnableRuleAttributesMustMatch property enables the validation rule that checks if attributes match. The default isfalse.

<PropertyGroup>  <ApiCompatEnableRuleAttributesMustMatch>true</ApiCompatEnableRuleAttributesMustMatch></PropertyGroup>

ApiCompatEnableRuleCannotChangeParameterName

When set totrue, theApiCompatEnableRuleCannotChangeParameterName property enables the validation rule that checks whether parameter names have changed in public methods. The default isfalse.

<PropertyGroup>  <ApiCompatEnableRuleCannotChangeParameterName>true</ApiCompatEnableRuleCannotChangeParameterName></PropertyGroup>

ApiCompatExcludeAttributesFile

TheApiCompatExcludeAttributesFile item specifies the path to a file that contains attributes to exclude inDocId format.

<ItemGroup>  <ApiCompatExcludeAttributesFile Include="ApiCompatExcludedAttributes.txt" />  <ApiCompatExcludeAttributesFile Include="ApiCompatBaselineExcludedAttributes.txt" /></ItemGroup>

ApiCompatGenerateSuppressionFile

TheApiCompatGenerateSuppressionFile property specifies whether to generate a compatibility suppression file.

<PropertyGroup>  <ApiCompatGenerateSuppressionFile>true</ApiCompatGenerateSuppressionFile></PropertyGroup>

ApiCompatPermitUnnecessarySuppressions

TheApiCompatPermitUnnecessarySuppressions property specifies whether to permit unnecessary suppressions in the suppression file.

The default isfalse.

<PropertyGroup>  <ApiCompatPermitUnnecessarySuppressions>true</ApiCompatPermitUnnecessarySuppressions></PropertyGroup>

ApiCompatPreserveUnnecessarySuppressions

TheApiCompatPreserveUnnecessarySuppressions property specifies whether to preserve unnecessary suppressions when regenerating the suppression file. When an existing suppression file is regenerated, its content is read, deserialized into a set of suppressions, and then stored in a list. Some of the suppressions might no longer be necessary if the incompatibility has been fixed. When the suppressions are serialized back to disk, you can choose to keepall the existing (deserialized) expressions by setting this property totrue.

The default isfalse.

<PropertyGroup>  <ApiCompatPreserveUnnecessarySuppressions>true</ApiCompatPreserveUnnecessarySuppressions></PropertyGroup>

ApiCompatRespectInternals

TheApiCompatRespectInternals property specifies whetherinternal APIs should be checked for compatibility in addition topublic APIs.

<PropertyGroup>  <ApiCompatRespectInternals>true</ApiCompatRespectInternals></PropertyGroup>

ApiCompatSuppressionFile

TheApiCompatSuppressionFile item specifies the path to one or more suppression files to read from. If unspecified, the suppression file<project-directory>/CompatibilitySuppressions.xml is read (if it exists).

<ItemGroup>  <ApiCompatSuppressionFile Include="CompatibilitySuppressions.xml;CompatibilitySuppressions.WasmThreads.xml" /></ItemGroup>

ApiCompatSuppressionOutputFile

TheApiCompatSuppressionOutputFile property specifies the path to a suppression file to write to when<ApiCompatGenerateSuppressionFile> istrue. If unspecified, the firstApiCompatSuppressionFile item is used.

EnablePackageValidation

TheEnablePackageValidation property enables a series of validations on the package after thePack task. For more information, seepackage validation.

<PropertyGroup>  <EnablePackageValidation>true</EnablePackageValidation></PropertyGroup>

EnableStrictModeForBaselineValidation

When set totrue, theEnableStrictModeForBaselineValidation property enablesstrict mode for package baseline checks. The default isfalse.

EnableStrictModeForCompatibleFrameworksInPackage

When set totrue, theEnableStrictModeForCompatibleFrameworksInPackage property enablesstrict mode for assemblies that are compatible based on their target framework. The default isfalse.

EnableStrictModeForCompatibleTfms

When set totrue, theEnableStrictModeForCompatibleTfms property enablesstrict mode for contract and implementation assemblies for all compatible target frameworks. The default istrue.

NoWarn

TheNoWarn property specifies the diagnostic IDs to suppress.

<PropertyGroup>  <NoWarn>$(NoWarn);PKV0001</NoWarn></PropertyGroup>

PackageValidationBaselineFrameworkToIgnore

ThePackageValidationBaselineFrameworkToIgnore item specifies a target framework to ignore from the baseline package. The framework string must exactly match the folder name in the baseline package.

<ItemGroup>  <PackageValidationBaselineFrameworkToIgnore Include="netcoreapp2.1" /></ItemGroup>

PackageValidationBaselineName

ThePackageValidationBaselineName property specifies the name of the baseline package to validate the current package against. If unspecified, thePackageId value is used.

PackageValidationBaselineVersion

ThePackageValidationBaselineVersion property specifies the version of the baseline package to validate the current package against.

PackageValidationReferencePath

ThePackageValidationReferencePath item specifies the directory path where the reference assembly can be found per TFM.

<ItemGroup>  <PackageValidationReferencePath Include="path/to/reference-assembly" TargetFramework="net7.0" /></ItemGroup>

RoslynAssembliesPath

TheRoslynAssembliesPath property specifies the path to the directory that contains the Microsoft.CodeAnalysis assemblies you want to use. You only need to set this property if you want to test with a newer compiler than what's in the SDK.

Publish-related properties

The following MSBuild properties are documented in this section:

AppendTargetFrameworkToOutputPath

TheAppendTargetFrameworkToOutputPath property controls whether thetarget framework moniker (TFM) is appended to the output path (which is defined byOutputPath). The .NET SDK automatically appends the target framework and, if present, the runtime identifier to the output path. SettingAppendTargetFrameworkToOutputPath tofalse prevents the TFM from being appended to the output path. However, without the TFM in the output path, multiple build artifacts may overwrite each other.

For example, for a .NET 5 app, the output path changes frombin\Debug\net5.0 tobin\Debug with the following setting:

<PropertyGroup>  <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath></PropertyGroup>

AppendRuntimeIdentifierToOutputPath

TheAppendRuntimeIdentifierToOutputPath property controls whether theruntime identifier (RID) is appended to the output path. The .NET SDK automatically appends the target framework and, if present, the runtime identifier (RID) to the output path. SettingAppendRuntimeIdentifierToOutputPath tofalse prevents the RID from being appended to the output path. (However, the RIDis still appended to the publish path. For more information, seedotnet/sdk#12114.)

For example, for a .NET 9 app and an RID ofwin-x64, the following setting changes the output path frombin\Debug\net9.0\win-x64 tobin\Debug\net9.0:

<PropertyGroup>  <AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath></PropertyGroup>

CopyLocalLockFileAssemblies

TheCopyLocalLockFileAssemblies property is useful for plugin projects that have dependencies on other libraries. If you set this property totrue, any transitive NuGet package dependencies are copied to the output directory. That means you can use the output ofdotnet build to run your plugin on any machine.

<PropertyGroup>  <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies></PropertyGroup>

The default value ofCopyLocalLockFileAssemblies can vary based on the output type. For example, for class libraries the default value isfalse, while for console applications the default istrue. You can specify this property explicitly to override the default if needed.

Tip

Alternatively, you can usedotnet publish to publish the class library. For more information, seedotnet publish.

ErrorOnDuplicatePublishOutputFiles

TheErrorOnDuplicatePublishOutputFiles property relates to whether the SDK generates error NETSDK1148 when MSBuild detects duplicate files in the publish output, but can't determine which files to remove. Set theErrorOnDuplicatePublishOutputFiles property tofalse if you don't want the error to be generated.

<PropertyGroup>  <ErrorOnDuplicatePublishOutputFiles>false</ErrorOnDuplicatePublishOutputFiles></PropertyGroup>

This property was introduced in .NET 6.

GenerateRuntimeConfigDevFile

Starting with the .NET 6 SDK, the[Appname].runtimesettings.dev.json file isno longer generated by default at compile time. If you still want this file to be generated, set theGenerateRuntimeConfigDevFile property totrue.

<PropertyGroup>  <GenerateRuntimeConfigDevFile>true</GenerateRuntimeConfigDevFile></PropertyGroup>

GenerateRuntimeConfigurationFiles

TheGenerateRuntimeConfigurationFiles property controls whether runtime configuration options are copied from theruntimeconfig.template.json file to the[appname].runtimeconfig.json file. For apps that require aruntimeconfig.json file, that is, those whoseOutputType isExe, this property defaults totrue.

<PropertyGroup>  <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles></PropertyGroup>

GenerateSatelliteAssembliesForCore

TheGenerateSatelliteAssembliesForCore property controls whether satellite assemblies are generated usingcsc.exe orAl.exe (Assembly Linker) in .NET Framework projects. (.NET Core and .NET 5+ projects always usecsc.exe to generate satellite assemblies.) For .NET Framework projects, satellite assemblies are created byal.exe, by default. By setting theGenerateSatelliteAssembliesForCore property totrue, satellite assemblies are created bycsc.exe instead. Usingcsc.exe can be advantageous in the following situations:

<PropertyGroup>  <GenerateSatelliteAssembliesForCore>true</GenerateSatelliteAssembliesForCore></PropertyGroup>

IsPublishable

TheIsPublishable property allows thePublish target to run. This property only affects processes that use.*proj files and thePublish target, such as thedotnet publish command. It does not affect publishing in Visual Studio, which uses thePublishOnly target. The default value istrue.

This property is useful if you rundotnet publish on a solution file, as it allows automatic selection of projects that should be published.

<PropertyGroup>  <IsPublishable>false</IsPublishable></PropertyGroup>

PreserveCompilationContext

ThePreserveCompilationContext property allows a built or published application to compile more code at run time using the same settings that were used at build time. The assemblies referenced at build time will be copied into theref subdirectory of the output directory. The names of the reference assemblies are stored in the application's.deps.json file along with the options passed to the compiler. You can retrieve this information using theDependencyContext.CompileLibraries andDependencyContext.CompilationOptions properties.

This functionality is mostly used internally by ASP.NET Core MVC and Razor pages to support run-time compilation of Razor files.

<PropertyGroup>  <PreserveCompilationContext>true</PreserveCompilationContext></PropertyGroup>

PreserveCompilationReferences

ThePreserveCompilationReferences property is similar to thePreserveCompilationContext property, except that it only copies the referenced assemblies to the publish directory, and not the.deps.json file.

<PropertyGroup>  <PreserveCompilationReferences>true</PreserveCompilationReferences></PropertyGroup>

For more information, seeRazor SDK properties.

ProduceReferenceAssemblyInOutDir

In .NET 5 and earlier versions, reference assemblies are always written to theOutDir directory. In .NET 6 and later versions, you can use theProduceReferenceAssemblyInOutDir property to control whether reference assemblies are written to theOutDir directory. The default value isfalse, and reference assemblies are only written to theIntermediateOutputPath directory. Set the value totrue to write reference assemblies to theOutDir directory.

<PropertyGroup>  <ProduceReferenceAssemblyInOutDir>true</ProduceReferenceAssemblyInOutDir></PropertyGroup>

For more information, seeWrite reference assemblies to intermediate output.

PublishDocumentationFile

When this property istrue, the XML documentation file for the project, if one is generated, is included in the publish output for the project. This property defaults totrue.

Tip

SetGenerateDocumentationFile totrue to generate an XML documentation file at compile time.

PublishDocumentationFiles

This property is an enablement flag for several other properties that control whether various kinds of XML documentation files are copied to the publish directory by default, namelyPublishDocumentationFile andPublishReferencesDocumentationFiles. If those properties are unset, and this property is set, then those properties will default totrue. This property defaults totrue.

PublishReferencesDocumentationFiles

When this property istrue, XML documentation files for the project's references are copied to the publish directory, instead of just run-time assets like DLL files. This property defaults totrue.

PublishRelease

ThePublishRelease property informsdotnet publish to use theRelease configuration by default instead of theDebug configuration. This property was introduced in .NET 7.

<PropertyGroup>  <PublishRelease>true</PublishRelease></PropertyGroup>

Note

  • Starting in the .NET 8 SDK,PublishRelease defaults totrue for projects that target .NET 8 or later. For more information, see'dotnet publish' uses Release configuration.
  • This property does not affect the behavior ofdotnet build /t:Publish, and it only changes the configuration only when publishing via the .NET CLI.
  • .NET 7 SDK only: To usePublishRelease in a project that's part of a Visual Studio solution, you must set the environment variableDOTNET_CLI_ENABLE_PUBLISH_RELEASE_FOR_SOLUTIONS totrue (or any other value). When publishing a solution with this variable enabled, the executable project'sPublishRelease value takes precedence and flows the new default configuration to any other projects in the solution. If a solution contains multiple executable or top-level projects with differing values ofPublishRelease, the solution won't successfully publish. For solutions that have many projects, use of this setting increases the time required to publish.

PublishSelfContained

ThePublishSelfContained property informsdotnet publish to publish an app as aself-contained app. This property is useful when you can't use the--self-contained argument for thedotnet publish command—for example, when you're publishing at the solution level. In that case, you can add thePublishSelfContained MSBuild property to a project orDirectory.Build.Props file.

This property was introduced in .NET 7. It's similar to theSelfContained property, except that it's specific to thepublish verb. It's recommended to usePublishSelfContained instead ofSelfContained.

<PropertyGroup>  <PublishSelfContained>true</PublishSelfContained></PropertyGroup>

RollForward

TheRollForward property controls how the application chooses a runtime when multiple runtime versions are available. This value is output to the.runtimeconfig.json as therollForward setting.

<PropertyGroup>  <RollForward>LatestMinor</RollForward></PropertyGroup>

SetRollForward to one of the following values:

ValueDescription
MinorDefault if not specified.
Roll-forward to the next available higher minor version (and highest available patch version within that minor version), if requested minor version is missing. If the requested minor version is present, then theLatestPatch policy is used.
MajorRoll-forward to the next available higher major version (at its lowest available minor version, and highest available patch version within that minor version), if requested major version is missing. If the requested major version is present, then theMinor policy is used.
LatestPatchRoll-forward to the highest patch version available for the requested major and minor versions. This value disables minor version roll-forward.
LatestMinorRoll-forward to the highest minor version available for the requested major version (and highest available patch version within that minor version), even if requested minor version is present.
LatestMajorRoll-forward to highest available major version (and highest available minor and patch version within that major version), even if requested major is present.
DisableDon't roll-forward, only bind to the specified version. This policy isn't recommended for general use since it disables the ability to roll-forward to the latest patches. This value is only recommended for testing.

For more information, seeControl roll-forward behavior.

RuntimeFrameworkVersion

TheRuntimeFrameworkVersion property specifies the version of the runtime to use when publishing. Specify a runtime version:

<PropertyGroup>  <RuntimeFrameworkVersion>5.0.7</RuntimeFrameworkVersion></PropertyGroup>

When publishing a framework-dependent application, this value specifies theminimum version required. When publishing a self-contained application, this value specifies theexact version required.

RuntimeIdentifier

TheRuntimeIdentifier property lets you specify a singleruntime identifier (RID) for the project. The RID enables publishing a self-contained deployment.

<PropertyGroup>  <RuntimeIdentifier>linux-x64</RuntimeIdentifier></PropertyGroup>

RuntimeIdentifiers

TheRuntimeIdentifiers property lets you specify a semicolon-delimited list ofruntime identifiers (RIDs) for the project. Use this property if you need to publish for multiple runtimes.RuntimeIdentifiers is used at restore time to ensure the right assets are in the graph.

Tip

RuntimeIdentifier (singular) can provide faster builds when only a single runtime is required.

<PropertyGroup>  <RuntimeIdentifiers>win-x64;osx-x64;linux-x64</RuntimeIdentifiers></PropertyGroup>

SatelliteResourceLanguages

TheSatelliteResourceLanguages property lets you specify which languages you want to preserve satellite resource assemblies for during build and publish. Many NuGet packages include localized resource satellite assemblies in the main package. For projects that reference these NuGet packages that don't require localized resources, the localized assemblies can unnecessarily inflate the build and publish output size. By adding theSatelliteResourceLanguages property to your project file, only localized assemblies for the languages you specify will be included in the build and publish output. For example, in the following project file, only English (US) and German (Germany) resource satellite assemblies will be retained.

<PropertyGroup>  <SatelliteResourceLanguages>en-US;de-DE</SatelliteResourceLanguages></PropertyGroup>

Note

  • You must specify this property in the project that references the NuGet package with localized resource satellite assemblies.

  • To specify multiple languages as an argument todotnet publish, you must addthree pairs of quotation marks around the language identifiers. For example:

    dotnet msbuild multi.msbuildproj -p:SatelliteResourceLanguages="""de;en"""

SelfContained

TheSelfContained property informsdotnet build anddotnet publish to build or publish an app as aself-contained app. This property is useful when you can't use the--self-contained argument with thedotnet command—for example, when you're publishing at the solution level. In that case, you can add theSelfContained MSBuild property to a project orDirectory.Build.Props file.

This property is similar to thePublishSelfContained property. It's recommended to usePublishSelfContained instead ofSelfContained when possible.

<PropertyGroup>  <SelfContained>true</SelfContained></PropertyGroup>

UseAppHost

TheUseAppHost property controls whether or not a native executable is created for a deployment. A native executable is required for self-contained deployments. A framework-dependent executable is created by default. Set theUseAppHost property tofalse to disable generation of the executable.

<PropertyGroup>  <UseAppHost>false</UseAppHost></PropertyGroup>

For more information about deployment, see.NET application deployment.

Trim-related properties

Numerous MSBuild properties are available to fine tune trimming, which is a feature that trims unused code from self-contained deployments. These options are discussed in detail atTrimming options. The following table provides a quick reference.

PropertyValuesDescription
PublishTrimmedtrue orfalseControls whether trimming is enabled during publish.
TrimModefull orpartialDefault isfull. Controls the trimming granularity.
SuppressTrimAnalysisWarningstrue orfalseControls whether trim analysis warnings are produced.
EnableTrimAnalyzertrue orfalseControls whether a subset of trim analysis warnings are produced. You can enable analysis even ifPublishTrimmed is set tofalse.
ILLinkTreatWarningsAsErrorstrue orfalseControls whether trim warnings are treated as errors. For example, you may want to set this property tofalse whenTreatWarningsAsErrors is set totrue.
TrimmerSingleWarntrue orfalseControls whether a single warning per assembly is shown or all warnings.
TrimmerRemoveSymbolstrue orfalseControls whether all symbols are removed from a trimmed application.

Build-related properties

The following MSBuild properties are documented in this section:

C# compiler options, such asLangVersion andNullable, can also be specified as MSBuild properties in your project file. For more information, seeC# compiler options.

ContinuousIntegrationBuild

TheContinuousIntegrationBuild property indicates whether a build is executing on a continuous integration (CI) server. When set totrue, this property enables settings that only apply to official builds as opposed to local builds on a developer machine. For example, stored file paths are normalized for official builds. But on a local development machine, the debugger isn't able to find local source files if file paths are normalized.

Note

Currently, setting this property totrue works only if you add either a specificSourceLink provider package reference or a<SourceRoot Include="$(MyDirectory)" /> item. For more information, seedotnet/roslyn issue 55860.

You can use your CI system's variable to conditionally set theContinuousIntegrationBuild property. For example, the variable name for Azure Pipelines isTF_BUILD:

<PropertyGroup Condition="'$(TF_BUILD)' == 'true'">  <ContinuousIntegrationBuild>true</ContinuousIntegrationBuild></PropertyGroup>

For GitHub Actions, the variable name isGITHUB_ACTIONS:

<PropertyGroup Condition="'$(GITHUB_ACTIONS)' == 'true'">  <ContinuousIntegrationBuild>true</ContinuousIntegrationBuild></PropertyGroup>

CopyDebugSymbolFilesFromPackages

When this property is set totrue, all symbol files (also known as PDB files) fromPackageReference items in the project are copied to the build output. These files can provide more informative stack traces for exceptions and make memory dumps and traces of the running application easier to understand. However, including these files results in an increased deployment bundle size.

This property was introduced in .NET SDK 7.0.100, though it defaults to not being specified.

CopyDocumentationFilesFromPackages

When this property is set totrue, all generated XML documentation files fromPackageReference items in the project are copied to the build output. Note that enabling this feature will result in increased deployment bundle size.

This property was introduced in .NET SDK 7.0.100, though it defaults to not being specified.

DisableImplicitFrameworkDefines

TheDisableImplicitFrameworkDefines property controls whether or not the SDK generates preprocessor symbols for the target framework and platform for the .NET project. When this property is set tofalse or is unset (which is the default value) preprocessor symbols are generated for:

  • Framework without version (NETFRAMEWORK,NETSTANDARD,NET)
  • Framework with version (NET48,NETSTANDARD2_0,NET6_0)
  • Framework with version minimum bound (NET48_OR_GREATER,NETSTANDARD2_0_OR_GREATER,NET6_0_OR_GREATER)

For more information on target framework monikers and these implicit preprocessor symbols, seeTarget frameworks.

Additionally, if you specify an operating system-specific target framework in the project (for examplenet6.0-android), the following preprocessor symbols are generated:

  • Platform without version (ANDROID,IOS,WINDOWS)
  • Platform with version (IOS15_1)
  • Platform with version minimum bound (IOS15_1_OR_GREATER)

For more information on operating system-specific target framework monikers, seeOS-specific TFMs.

Finally, if your target framework implies support for older target frameworks, preprocessor symbols for those older frameworks are emitted. For example,net6.0implies support fornet5.0 and so on all the way back to.netcoreapp1.0. So for each of these target frameworks, theFramework with version minimum bound symbol will be defined.

DocumentationFile

TheDocumentationFile property lets you specify a file name for the XML file that contains the documentation for your library. For IntelliSense to function correctly with your documentation, the file name must be the same as the assembly name and must be in the same directory as the assembly. If you don't specify this property but you do setGenerateDocumentationFile totrue, the name of the documentation file defaults to the name of your assembly but with an.xml file extension. For this reason, it's often easier to omit this property and use theGenerateDocumentationFile property instead.

If you specify this property but you setGenerateDocumentationFile tofalse, the compilerdoes not generate a documentation file. If you specify this property and omit theGenerateDocumentationFile property, the compilerdoes generate a documentation file.

<PropertyGroup>  <DocumentationFile>path/to/file.xml</DocumentationFile></PropertyGroup>

EmbeddedResourceUseDependentUponConvention

TheEmbeddedResourceUseDependentUponConvention property defines whether resource manifest file names are generated from type information in source files that are co-located with resource files. For example, ifForm1.resx is in the same folder asForm1.cs, andEmbeddedResourceUseDependentUponConvention is set totrue, the generated.resources file takes its name from the first type that's defined inForm1.cs. IfMyNamespace.Form1 is the first type defined inForm1.cs, the generated file name isMyNamespace.Form1.resources.

Note

IfLogicalName,ManifestResourceName, orDependentUpon metadata is specified for anEmbeddedResource item, the generated manifest file name for that resource file is based on that metadata instead.

By default, in a new .NET project that targets .NET Core 3.0 or a later version, this property is set totrue. If set tofalse, and noLogicalName,ManifestResourceName, orDependentUpon metadata is specified for theEmbeddedResource item in the project file, the resource manifest file name is based off the root namespace for the project and the relative file path to the.resx file. For more information, seeHow resource manifest files are named.

<PropertyGroup>  <EmbeddedResourceUseDependentUponConvention>true</EmbeddedResourceUseDependentUponConvention></PropertyGroup>

EnablePreviewFeatures

TheEnablePreviewFeatures property defines whether your project depends on any APIs or assemblies that are decorated with theRequiresPreviewFeaturesAttribute attribute. This attribute is used to signify that an API or assembly uses features that are considered to be inpreview for the SDK version you're using. Preview features are not supported and may be removed in a future version. To enable the use of preview features, set the property toTrue.

<PropertyGroup>  <EnablePreviewFeatures>True</EnablePreviewFeatures></PropertyGroup>

When a project contains this property set toTrue, the following assembly-level attribute is added to theAssemblyInfo.cs file:

[assembly: RequiresPreviewFeatures]

An analyzer warns if this attribute is present on dependencies for projects whereEnablePreviewFeatures is not set toTrue.

Library authors who intend to ship preview assemblies should set this property toTrue. If an assembly needs to ship with a mixture of preview and non-preview APIs, see theGenerateRequiresPreviewFeaturesAttribute section below.

EnableWindowsTargeting

Set theEnableWindowsTargeting property totrue to build Windows apps (for example, Windows Forms or Windows Presentation Foundation apps) on a non-Windows platform. If you don't set this property totrue, you'll get build warningNETSDK1100. This error occurs because targeting and runtime packs aren't automatically downloaded on platforms that aren't supported. By setting this property, those packs are downloaded when cross-targeting.

Note

This property is currently recommended to allow development on non-Windows platforms. But when the application is ready to be released, it should be built on Windows. When building on a non-Windows platform, the output may not be the same as when building on Windows. In particular, the executable is not marked as a Windows application (which means that it will always launch a console window) and won't have an icon embedded.

<PropertyGroup>  <EnableWindowsTargeting>true</EnableWindowsTargeting></PropertyGroup>

GenerateDocumentationFile

TheGenerateDocumentationFile property controls whether the compiler generates an XML documentation file for your library. If you set this property totrue and you don't specify a file name via theDocumentationFile property, the generated XML file is placed in the same output directory as your assembly and has the same file name (but with an.xml extension).

<PropertyGroup>  <GenerateDocumentationFile>true</GenerateDocumentationFile></PropertyGroup>

For more information about generating documentation from code comments, seeXML documentation comments (C#),Document your code with XML (Visual Basic), orDocument your code with XML (F#).

GenerateRequiresPreviewFeaturesAttribute

TheGenerateRequiresPreviewFeaturesAttribute property is closely related to theEnablePreviewFeatures property. If your library uses preview features but you don't want the entire assembly to be marked with theRequiresPreviewFeaturesAttribute attribute, which would require any consumers toenable preview features, set this property toFalse.

<PropertyGroup>    <EnablePreviewFeatures>True</EnablePreviewFeatures>    <GenerateRequiresPreviewFeaturesAttribute>False</GenerateRequiresPreviewFeaturesAttribute></PropertyGroup>

Important

If you set theGenerateRequiresPreviewFeaturesAttribute property toFalse, you must be certain to decorate all public APIs that rely on preview features withRequiresPreviewFeaturesAttribute.

OptimizeImplicitlyTriggeredBuild

To speed up the build time, builds that are implicitly triggered by Visual Studio skip code analysis, including nullable analysis. Visual Studio triggers an implicit build when you run tests, for example. However, implicit builds are optimized only whenTreatWarningsAsErrors is nottrue. If you haveTreatWarningsAsErrors set totrue but you still want implicitly triggered builds to be optimized, you can setOptimizeImplicitlyTriggeredBuild toTrue. To turn off build optimization for implicitly triggered builds, setOptimizeImplicitlyTriggeredBuild toFalse.

<PropertyGroup>    <OptimizeImplicitlyTriggeredBuild>True</OptimizeImplicitlyTriggeredBuild></PropertyGroup>

DisableRuntimeMarshalling

TheDisableRuntimeMarshalling property enables you to specify that you would like to disable runtime marshalling support for your project. If this property is set totrue, then theDisableRuntimeMarshallingAttribute is added to the assembly and any P/Invokes or delegate-based interop will follow the rules fordisabled runtime marshalling.

<PropertyGroup>    <DisableRuntimeMarshalling>True</DisableRuntimeMarshalling></PropertyGroup>

BuildWithNetFrameworkHostedCompiler

SpecifyingBuildWithNetFrameworkHostedCompiler=true is the equivalent of specifyingRoslynCompilerType=FrameworkPackage. For more information, seeRoslynCompilerType.SpecifyingBuildWithNetFrameworkHostedCompiler=false ensures the automatic opt in toRoslynCompilerType=FrameworkPackage does not happen.IfRoslynCompilerType is specified explicitly,BuildWithNetFrameworkHostedCompiler has no effect.

RoslynCompilerType

TheRoslynCompilerType property controls the version of the C# or Visual Basic compiler. The following values are recognized:

  • Core: Use the compiler that comes with the .NET SDK. This is the default since .NET 10, even when using .NET Framework MSBuild.
  • Framework: Use the compiler that comes with .NET Framework MSBuild.
  • FrameworkPackage: When using .NET Framework MSBuild, download and use a package with the .NET Framework compiler that corresponds to the .NET SDK version.

Default item inclusion properties

The following MSBuild properties are documented in this section:

For more information, seeDefault includes and excludes.

DefaultItemExcludes

Use theDefaultItemExcludes property to define glob patterns for files and folders that should be excluded from the include, exclude, and remove globs. By default, the./bin and./obj folders are excluded from the glob patterns.

<PropertyGroup>  <DefaultItemExcludes>$(DefaultItemExcludes);**/*.myextension</DefaultItemExcludes></PropertyGroup>

DefaultItemExcludesInProjectFolder

Use theDefaultItemExcludesInProjectFolder property to define glob patterns for files and folders in the project folder that should be excluded from the include, exclude, and remove globs. By default, folders that start with a period (.), such as.git and.vs, are excluded from the glob patterns.

This property is very similar to theDefaultItemExcludes property, except that it only considers files and folders in the project folder. When a glob pattern would unintentionally match items outside the project folder with a relative path, use theDefaultItemExcludesInProjectFolder property instead of theDefaultItemExcludes property.

<PropertyGroup>  <DefaultItemExcludesInProjectFolder>$(DefaultItemExcludesInProjectFolder);**/myprefix*/**</DefaultItemExcludesInProjectFolder></PropertyGroup>

EnableDefaultItems

TheEnableDefaultItems property controls whether compile items, embedded resource items, andNone items are implicitly included in the project. The default value istrue. Set theEnableDefaultItems property tofalse to disable all implicit file inclusion.

<PropertyGroup>  <EnableDefaultItems>false</EnableDefaultItems></PropertyGroup>

EnableDefaultCompileItems

TheEnableDefaultCompileItems property controls whether compile items are implicitly included in the project. The default value istrue. Set theEnableDefaultCompileItems property tofalse to disable implicit inclusion of *.cs and other language-extension files.

<PropertyGroup>  <EnableDefaultCompileItems>false</EnableDefaultCompileItems></PropertyGroup>

EnableDefaultEmbeddedResourceItems

TheEnableDefaultEmbeddedResourceItems property controls whether embedded resource items are implicitly included in the project. The default value istrue. Set theEnableDefaultEmbeddedResourceItems property tofalse to disable implicit inclusion of embedded resource files.

<PropertyGroup>  <EnableDefaultEmbeddedResourceItems>false</EnableDefaultEmbeddedResourceItems></PropertyGroup>

EnableDefaultNoneItems

TheEnableDefaultNoneItems property controls whetherNone items (files that have no role in the build process) are implicitly included in the project. The default value istrue. Set theEnableDefaultNoneItems property tofalse to disable implicit inclusion ofNone items.

<PropertyGroup>  <EnableDefaultNoneItems>false</EnableDefaultNoneItems></PropertyGroup>

Code analysis properties

The following MSBuild properties are documented in this section:

AnalysisLevel

TheAnalysisLevel property lets you specify a set of code analyzers to run according to a .NET release. Each .NET release has a set of code analysis rules. Of that set, the rules that are enabled by default for that release analyze your code. For example, if you upgrade from .NET 8 to .NET 9 but don't want the default set of code analysis rules to change, setAnalysisLevel to8.

<PropertyGroup>  <AnalysisLevel>8</AnalysisLevel></PropertyGroup>

Optionally, you can specify a compound value for this property that also specifies how aggressively to enable rules. Compound values take the form<version>-<mode>, where the<mode> value is one of theAnalysisMode values. The following example uses thepreview version of code analyzers, and enables therecommended set of rules.

<PropertyGroup>  <AnalysisLevel>preview-recommended</AnalysisLevel></PropertyGroup>

Default value:

  • If your project targets .NET 5 or later, or if you've added theAnalysisMode property, the default value islatest.
  • Otherwise, this property is omitted unless you explicitly add it to the project file.

The following table shows the values you can specify.

ValueMeaning
latestThe latest code analyzers that have been released are used. This is the default.
latest-<mode>The latest code analyzers that have been released are used. The<mode> value determines which rules are enabled.
previewThe latest code analyzers are used, even if they are in preview.
preview-<mode>The latest code analyzers are used, even if they are in preview. The<mode> value determines which rules are enabled.
9.0The set of rules that was available for the .NET 9 release is used, even if newer rules are available.
9.0-<mode>The set of rules that was available for the .NET 9 release is used, even if newer rules are available. The<mode> value determines which rules are enabled.
9The set of rules that was available for the .NET 9 release is used, even if newer rules are available.
9-<mode>The set of rules that was available for the .NET 9 release is used, even if newer rules are available. The<mode> value determines which rules are enabled.
8.0The set of rules that was available for the .NET 8 release is used, even if newer rules are available.
8.0-<mode>The set of rules that was available for the .NET 8 release is used, even if newer rules are available. The<mode> value determines which rules are enabled.
8The set of rules that was available for the .NET 8 release is used, even if newer rules are available.
8-<mode>The set of rules that was available for the .NET 8 release is used, even if newer rules are available. The<mode> value determines which rules are enabled.
7.0The set of rules that was available for the .NET 7 release is used, even if newer rules are available.
7.0-<mode>The set of rules that was available for the .NET 7 release is used, even if newer rules are available. The<mode> value determines which rules are enabled.
7The set of rules that was available for the .NET 7 release is used, even if newer rules are available.
7-<mode>The set of rules that was available for the .NET 7 release is used, even if newer rules are available. The<mode> value determines which rules are enabled.

Note

  • If you setEnforceCodeStyleInBuild totrue, this property affectscode-style (IDEXXXX) rules (in addition to code-quality rules).
  • If you set a compound value forAnalysisLevel, you don't need to specify anAnalysisMode. However, if you do,AnalysisLevel takes precedence overAnalysisMode.
  • This property has no effect on code analysis in projects that don't reference aproject SDK, for example, legacy .NET Framework projects that reference the Microsoft.CodeAnalysis.NetAnalyzers NuGet package.

AnalysisLevel<Category>

This property is the same asAnalysisLevel, except that it only applies to a specificcategory of code-analysis rules. This property allows you to use a different version of code analyzers for a specific category, or to enable or disable rules at a different level to the other rule categories. If you omit this property for a particular category of rules, it defaults to theAnalysisLevel value. The available values are the same as those forAnalysisLevel.

<PropertyGroup>  <AnalysisLevelSecurity>preview</AnalysisLevelSecurity></PropertyGroup>
<PropertyGroup>  <AnalysisLevelSecurity>preview-recommended</AnalysisLevelSecurity></PropertyGroup>

The following table lists the property name for each rule category.

Property nameRule category
<AnalysisLevelDesign>Design rules
<AnalysisLevelDocumentation>Documentation rules
<AnalysisLevelGlobalization>Globalization rules
<AnalysisLevelInteroperability>Portability and interoperability rules
<AnalysisLevelMaintainability>Maintainability rules
<AnalysisLevelNaming>Naming rules
<AnalysisLevelPerformance>Performance rules
<AnalysisLevelSingleFile>Single-file application rules
<AnalysisLevelReliability>Reliability rules
<AnalysisLevelSecurity>Security rules
<AnalysisLevelStyle>Code-style (IDEXXXX) rules
<AnalysisLevelUsage>Usage rules

AnalysisMode

The .NET SDK ships with all of the"CA" code quality rules. By default, onlysome rules are enabled as build warnings in each .NET release. TheAnalysisMode property lets you customize the set of rules that's enabled by default. You can either switch to a more aggressive analysis mode where you can opt out of rules individually, or a more conservative analysis mode where you can opt in to specific rules. For example, if you want to enable all rules as build warnings, set the value toAll.

<PropertyGroup>  <AnalysisMode>All</AnalysisMode></PropertyGroup>

The following table shows the available option values. They're listed in increasing order of the number of rules they enable.

ValueDescription
NoneAll rules are disabled. You can selectivelyopt in to individual rules to enable them.
DefaultDefault mode, where certain rules are enabled as build warnings, certain rules are enabled as Visual Studio IDE suggestions, and the remainder are disabled.
MinimumMore aggressive mode thanDefault mode. Certain suggestions that are highly recommended for build enforcement are enabled as build warnings. To see which rules this includes, inspect the%ProgramFiles%/dotnet/sdk/[version]/Sdks/Microsoft.NET.Sdk/analyzers/build/config/analysislevel_[level]_minimum.globalconfig file. (For .NET 7 and earlier versions, the file extension is.editorconfig.)
RecommendedMore aggressive mode thanMinimum mode, where more rules are enabled as build warnings. To see which rules this includes, inspect the%ProgramFiles%/dotnet/sdk/[version]/Sdks/Microsoft.NET.Sdk/analyzers/build/config/analysislevel_[level]_recommended.globalconfig file. (For .NET 7 and earlier versions, the file extension is.editorconfig.)
AllAll rules are enabled as build warnings*. You can selectivelyopt out of individual rules to disable them.

* The following rules arenot enabled by settingAnalysisMode toAll or by settingAnalysisLevel tolatest-all: CA1017, CA1045, CA1005, CA1014, CA1060, CA1021, and the code metrics analyzer rules (CA1501, CA1502, CA1505, CA1506, and CA1509). These legacy rules might be deprecated in a future version. However, you can still enable them individually using adotnet_diagnostic.CAxxxx.severity = <severity> entry.

Note

  • If you setEnforceCodeStyleInBuild totrue, this property affectscode-style (IDEXXXX) rules (in addition to code-quality rules).
  • If you use a compound value forAnalysisLevel, for example,<AnalysisLevel>9-recommended</AnalysisLevel>, you can omit this property entirely. However, if you specify both properties,AnalysisLevel takes precedence overAnalysisMode.
  • This property has no effect on code analysis in projects that don't reference aproject SDK, for example, legacy .NET Framework projects that reference the Microsoft.CodeAnalysis.NetAnalyzers NuGet package.

AnalysisMode<Category>

This property is the same asAnalysisMode, except that it only applies to a specificcategory of code-analysis rules. This property allows you to enable or disable rules at a different level to the other rule categories. If you omit this property for a particular category of rules, it defaults to theAnalysisMode value. The available values are the same as those forAnalysisMode.

<PropertyGroup>  <AnalysisModeSecurity>All</AnalysisModeSecurity></PropertyGroup>

The following table lists the property name for each rule category.

Property nameRule category
<AnalysisModeDesign>Design rules
<AnalysisModeDocumentation>Documentation rules
<AnalysisModeGlobalization>Globalization rules
<AnalysisModeInteroperability>Portability and interoperability rules
<AnalysisModeMaintainability>Maintainability rules
<AnalysisModeNaming>Naming rules
<AnalysisModePerformance>Performance rules
<AnalysisModeSingleFile>Single-file application rules
<AnalysisModeReliability>Reliability rules
<AnalysisModeSecurity>Security rules
<AnalysisModeStyle>Code-style (IDEXXXX) rules
<AnalysisModeUsage>Usage rules

CodeAnalysisTreatWarningsAsErrors

TheCodeAnalysisTreatWarningsAsErrors property lets you configure whether code quality analysis warnings (CAxxxx) should be treated as warnings and break the build. If you use the-warnaserror flag when you build your projects,.NET code quality analysis warnings are also treated as errors. If you do not want code quality analysis warnings to be treated as errors, you can set theCodeAnalysisTreatWarningsAsErrors MSBuild property tofalse in your project file.

<PropertyGroup>  <CodeAnalysisTreatWarningsAsErrors>false</CodeAnalysisTreatWarningsAsErrors></PropertyGroup>

EnableNETAnalyzers

.NET code quality analysis is enabled, by default, for projects that target .NET 5 or a later version. If you're developing using the .NET 5+ SDK, you can enable .NET code analysis for SDK-style projects that target earlier versions of .NET by setting theEnableNETAnalyzers property totrue. To disable code analysis in any project, set this property tofalse.

<PropertyGroup>  <EnableNETAnalyzers>true</EnableNETAnalyzers></PropertyGroup>

Note

This property applies specifically to the built-in analyzers in the .NET 5+ SDK. It should not be used when you install a NuGet code analysis package.

EnforceCodeStyleInBuild

.NET code style analysis is disabled, by default, on build for all .NET projects. You can enable code style analysis for .NET projects by setting theEnforceCodeStyleInBuild property totrue.

<PropertyGroup>  <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild></PropertyGroup>

All code style rules that areconfigured to be warnings or errors will execute on build and report violations.

_SkipUpgradeNetAnalyzersNuGetWarning

The_SkipUpgradeNetAnalyzersNuGetWarning property lets you configure whether you receive a warning if you're using code analyzers from a NuGet package that's out-of-date when compared with the code analyzers in the latest .NET SDK. The warning looks similar to:

The .NET SDK has newer analyzers with version '6.0.0' than what version '5.0.3' of 'Microsoft.CodeAnalysis.NetAnalyzers' package provides. Update or remove this package reference.

To remove this warning and continue to use the version of code analyzers in the NuGet package, set_SkipUpgradeNetAnalyzersNuGetWarning totrue in your project file.

<PropertyGroup>  <_SkipUpgradeNetAnalyzersNuGetWarning>true</_SkipUpgradeNetAnalyzersNuGetWarning></PropertyGroup>

Runtime configuration properties

You can configure some runtime behaviors by specifying MSBuild properties in the project file of the app. For information about other ways of configuring runtime behavior, seeRuntime configuration settings.

AutoreleasePoolSupport

TheAutoreleasePoolSupport property configures whether each managed thread receives an implicitNSAutoreleasePool when running on a supported macOS platform. For more information, seeAutoreleasePool for managed threads.

<PropertyGroup>  <AutoreleasePoolSupport>true</AutoreleasePoolSupport></PropertyGroup>

ConcurrentGarbageCollection

TheConcurrentGarbageCollection property configures whetherbackground (concurrent) garbage collection is enabled. Set the value tofalse to disable background garbage collection. For more information, seeBackground GC.

<PropertyGroup>  <ConcurrentGarbageCollection>false</ConcurrentGarbageCollection></PropertyGroup>

InvariantGlobalization

TheInvariantGlobalization property configures whether the app runs inglobalization-invariant mode, which means it doesn't have access to culture-specific data. Set the value totrue to run in globalization-invariant mode. For more information, seeInvariant mode.

<PropertyGroup>  <InvariantGlobalization>true</InvariantGlobalization></PropertyGroup>

PredefinedCulturesOnly

In .NET 6 and later versions, thePredefinedCulturesOnly property configures whether apps can create cultures other than the invariant culture whenglobalization-invariant mode is enabled. The default istrue. Set the value tofalse to allow creation of any new culture in globalization-invariant mode.

<PropertyGroup>  <PredefinedCulturesOnly>false</PredefinedCulturesOnly></PropertyGroup>

For more information, seeCulture creation and case mapping in globalization-invariant mode.

RetainVMGarbageCollection

TheRetainVMGarbageCollection property configures the garbage collector to put deleted memory segments on a standby list for future use or release them. Setting the value totrue tells the garbage collector to put the segments on a standby list. For more information, seeRetain VM.

<PropertyGroup>  <RetainVMGarbageCollection>true</RetainVMGarbageCollection></PropertyGroup>

ServerGarbageCollection

TheServerGarbageCollection property configures whether the application usesworkstation garbage collection or server garbage collection. Set the value totrue to use server garbage collection. For more information, seeWorkstation vs. server.

<PropertyGroup>  <ServerGarbageCollection>true</ServerGarbageCollection></PropertyGroup>

ThreadPoolMaxThreads

TheThreadPoolMaxThreads property configures the maximum number of threads for the worker thread pool. For more information, seeMaximum threads.

<PropertyGroup>  <ThreadPoolMaxThreads>20</ThreadPoolMaxThreads></PropertyGroup>

ThreadPoolMinThreads

TheThreadPoolMinThreads property configures the minimum number of threads for the worker thread pool. For more information, seeMinimum threads.

<PropertyGroup>  <ThreadPoolMinThreads>4</ThreadPoolMinThreads></PropertyGroup>

TieredCompilation

TheTieredCompilation property configures whether the just-in-time (JIT) compiler usestiered compilation. Set the value tofalse to disable tiered compilation. For more information, seeTiered compilation.

<PropertyGroup>  <TieredCompilation>false</TieredCompilation></PropertyGroup>

TieredCompilationQuickJit

TheTieredCompilationQuickJit property configures whether the JIT compiler uses quick JIT. Set the value tofalse to disable quick JIT. For more information, seeQuick JIT.

<PropertyGroup>  <TieredCompilationQuickJit>false</TieredCompilationQuickJit></PropertyGroup>

TieredCompilationQuickJitForLoops

TheTieredCompilationQuickJitForLoops property configures whether the JIT compiler uses quick JIT on methods that contain loops. Set the value totrue to enable quick JIT on methods that contain loops. For more information, seeQuick JIT for loops.

<PropertyGroup>  <TieredCompilationQuickJitForLoops>true</TieredCompilationQuickJitForLoops></PropertyGroup>

TieredPGO

TheTieredPGO property controls whether dynamic or tiered profile-guided optimization (PGO) is enabled. Set the value totrue to enable tiered PGO. For more information, seeProfile-guided optimization.

<PropertyGroup>  <TieredPGO>true</TieredPGO></PropertyGroup>

UseWindowsThreadPool

TheUseWindowsThreadPool property configures whether thread pool thread management is delegated to the Windows thread pool (Windows only). The default value isfalse, in which case the .NET thread pool is used. For more information, seeWindows thread pool.

<PropertyGroup>  <UseWindowsThreadPool>true</UseWindowsThreadPool></PropertyGroup>

Reference-related properties

The following MSBuild properties are documented in this section:

AssetTargetFallback

TheAssetTargetFallback property lets you specify additional compatible framework versions for project references and NuGet packages. For example, if you specify a package dependency usingPackageReference but that package doesn't contain assets that are compatible with your projects'sTargetFramework, theAssetTargetFallback property comes into play. The compatibility of the referenced package is rechecked using each target framework that's specified inAssetTargetFallback. This property replaces the deprecated propertyPackageTargetFallback.

You can set theAssetTargetFallback property to one or moretarget framework versions.

<PropertyGroup>  <AssetTargetFallback>net461</AssetTargetFallback></PropertyGroup>

DisableImplicitFrameworkReferences

TheDisableImplicitFrameworkReferences property controls implicitFrameworkReference items when targeting .NET Core 3.0 and later versions. When targeting .NET Core 2.1 or .NET Standard 2.0 and earlier versions, it controls implicitPackageReference items to packages in a metapackage. (A metapackage is a framework-based package that consists only of dependencies on other packages.) This property also controls implicit references such asSystem andSystem.Core when targeting .NET Framework.

Set this property totrue to disable implicitFrameworkReference orPackageReference items. If you set this property totrue, you can add explicit references to just the frameworks or packages you need.

<PropertyGroup>  <DisableImplicitFrameworkReferences>true</DisableImplicitFrameworkReferences></PropertyGroup>

DisableTransitiveFrameworkReferenceDownloads

Set theDisableTransitiveFrameworkReferenceDownloads property totrue to avoid downloading extra runtime and targeting packs that aren't directly referenced by your project.

<PropertyGroup>  <DisableTransitiveFrameworkReferenceDownloads>true</DisableTransitiveFrameworkReferenceDownloads></PropertyGroup>

DisableTransitiveProjectReferences

TheDisableTransitiveProjectReferences property controls implicit project references. Set this property totrue to disable implicitProjectReference items. Disabling implicit project references results in non-transitive behavior similar to thelegacy project system.

When this property istrue, it has a similar effect to that of settingPrivateAssets="All" on all of the dependencies of the depended-upon project.

If you set this property totrue, you can add explicit references to just the projects you need.

<PropertyGroup>  <DisableTransitiveProjectReferences>true</DisableTransitiveProjectReferences></PropertyGroup>

ManagePackageVersionsCentrally

TheManagePackageVersionsCentrally property was introduced in .NET 7. By setting it totrue in aDirectory.Packages.props file in the root of your repository, you can manage common dependencies in your projects from one location. Add versions for common package dependencies usingPackageVersion items in theDirectory.Packages.props file. Then, in the individual project files, you can omitVersion attributes from anyPackageReference items that refer to centrally managed packages.

ExampleDirectory.Packages.props file:

<PropertyGroup>  <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally></PropertyGroup>...<ItemGroup>  <PackageVersion Include="Microsoft.Extensions.Configuration" Version="7.0.0" /></ItemGroup>

Individual project file:

<ItemGroup>  <PackageReference Include="Microsoft.Extensions.Configuration" /></ItemGroup>

For more information, seecentral package management (CPM).

Restore-related properties

Restoring a referenced package installs all of its direct dependencies and all the dependencies of those dependencies. You can customize package restoration by specifying properties such asRestorePackagesPath andRestoreIgnoreFailedSources. For more information about these and other properties, seerestore target.

<PropertyGroup>  <RestoreIgnoreFailedSource>true</RestoreIgnoreFailedSource></PropertyGroup>

UseMauiEssentials

Set theUseMauiEssentials property totrue to declare an explicit reference to a project or package that depends on MAUI Essentials. This setting ensures that your project pulls in the correct known framework reference for MAUI Essentials. If your project references a project that uses MAUI Essentials but you don't set this property totrue, you might encounter build warningNETSDK1186.

<PropertyGroup>  <UseMauiEssentials>true</UseMauiEssentials></PropertyGroup>

ValidateExecutableReferencesMatchSelfContained

TheValidateExecutableReferencesMatchSelfContained property can be used to disable errors related to executable project references. If .NET detects that a self-contained executable project references a framework-dependent executable project, or vice versa, it generates errors NETSDK1150 and NETSDK1151, respectively. To avoid these errors when the reference is intentional, set theValidateExecutableReferencesMatchSelfContained property tofalse.

<PropertyGroup>  <ValidateExecutableReferencesMatchSelfContained>false</ValidateExecutableReferencesMatchSelfContained></PropertyGroup>

WindowsSdkPackageVersion

TheWindowsSdkPackageVersion property can be used to override the version of theWindows SDK targeting package. This property was introduced in .NET 5, and replaces the use of theFrameworkReference item for this purpose.

<PropertyGroup>  <WindowsSdkPackageVersion>10.0.19041.18</WindowsSdkPackageVersion></PropertyGroup>

Note

We don't recommend overriding the Windows SDK version, because the Windows SDK targeting packages are included with the .NET 5+ SDK. Instead, to reference the latest Windows SDK package, update your version of the .NET SDK. This property should only be used in rare cases such as using preview packages or needing to override the version of C#/WinRT.

Run-related properties

The following properties are used for launching an app with thedotnet run command:

RunArguments

TheRunArguments property defines the arguments that are passed to the app when it's run.

<PropertyGroup>  <RunArguments>-mode dryrun</RunArguments></PropertyGroup>

Tip

You can specify additional arguments to be passed to the app by using the-- option fordotnet run.

RunWorkingDirectory

TheRunWorkingDirectory property defines the working directory for the application process to be started in. It can be an absolute path or a path that's relative to the project directory. If you don't specify a directory,OutDir is used as the working directory.

<PropertyGroup>  <RunWorkingDirectory>c:\temp</RunWorkingDirectory></PropertyGroup>

SDK-related properties

The following MSBuild properties are documented in this section:

SdkAnalysisLevel

Introduced in .NET 9, theSdkAnalysisLevel property can be used to configure howstrict SDK tooling is. It helps you manage SDK warning levels in situations where you might not be able to pin SDKs viaglobal.json or other means. You can use this property to tell a newer SDK to behave as if it were an older SDK, with regards to a specific tool or feature, without having to install the older SDK.

The allowed values of this property are SDK feature bands, for example, 8.0.100 and 8.0.400. The value defaults to the SDK feature band of the running SDK. For example, for SDK 9.0.102, the value would be 9.0.100. (For information about how the .NET SDK is versioned, seeHow .NET is versioned.)

<PropertyGroup>  <SdkAnalysisLevel>8.0.400</SdkAnalysisLevel></PropertyGroup>

For more information, seeSDK Analysis Level Property and Usage.

Microsoft.Testing.Platform–related properties

The following MSBuild properties are documented in this section:

IsTestingPlatformApplication

When your project references theMicrosoft.Testing.Platform.MSBuild package, settingIsTestingPlatformApplication totrue (which is also the default value if not specified) does the following:

  • Generates the entry point to the test project.
  • Generates the configuration file.
  • Detects the extensions.

Setting the property tofalse disables the transitive dependency to the package. Atransitive dependency is when a project that references another project that references a given package behaves as ifit references the package. You'd typically set this property tofalse in a non-test project that references a test project. For more information, seeerror CS8892.

If your test project references MSTest, NUnit, or xUnit, this property is set to the same value asEnableMSTestRunner,EnableNUnitRunner, orUseMicrosoftTestingPlatformRunner (for xUnit).

Enable[NugetPackageNameWithoutDots]

Use a property with the patternEnable[NugetPackageNameWithoutDots] to enable or disable Microsoft.Testing.Platform extensions.

For example, to enable the crash dump extension (NuGet packageMicrosoft.Testing.Extensions.CrashDump), set theEnableMicrosoftTestingExtensionsCrashDump totrue.

For more information, seeEnable or disable extensions.

EnableAspireTesting

When you use theMSTest project SDK, you can use theEnableAspireTesting property to bring in all the dependencies and defaultusing directives you need for testing withAspire andMSTest. This property is available in MSTest 3.4 and later versions.

For more information, seeTest with .NET Aspire.

EnablePlaywright

When you use theMSTest project SDK, you can use theEnablePlaywright property to bring in all the dependencies and defaultusing directives you need for testing withPlaywright andMSTest.This property is available in MSTest 3.4 and later versions.

For more information, seePlaywright.

EnableMSTestRunner

TheEnableMSTestRunner property enables or disables the use of theMSTest runner. The MSTest runner is a lightweight and portable alternative to VSTest. This property is available in MSTest 3.2 and later versions.

Note

If your project specifies theMSTest SDK, you don't need to set this property. It's set automatically.

EnableNUnitRunner

TheEnableNUnitRunner property enables or disables the use of theNUnit runner. The NUnit runner is a lightweight and portable alternative to VSTest. This property is available inNUnit3TestAdapter in version 5.0 and later.

UseMicrosoftTestingPlatformRunner

TheUseMicrosoftTestingPlatformRunner property enables or disables the use of Microsoft.Testing.Platform runner inxUnit.v3 test projects.

GenerateTestingPlatformEntryPoint

Setting theGenerateTestingPlatformEntryPoint property tofalse disables the automatic generation of the program entry point in test projects that useMicrosoft.Testing.Platform. You might want to set this property tofalse when you manually define an entry point, or when you reference a test project from an executable that also has an entry point.

For more information, seeerror CS8892.

To control the generation of the entry point in a VSTest project, use theGenerateProgramFile property.

GenerateTestingPlatformConfigurationFile

TheGenerateTestingPlatformConfigurationFile property is only available whenIsTestingPlatformApplication istrue. It's used to allow the copy and rename of theconfig file in the output folder.

TestingPlatformCaptureOutput

TheTestingPlatformCaptureOutput property controls whether all console output that a test executable writes is captured and hidden from the user when you usedotnet test to runMicrosoft.Testing.Platform tests. By default, the console output is hidden. This output includes the banner, version information, and formatted test information. Set this property tofalse to show this information together with MSBuild output.

For more information, seeShow complete platform output.

TestingPlatformCommandLineArguments

TheTestingPlatformCaptureOutput property lets you specify command-line arguments to the test app when you usedotnet test to runMicrosoft.Testing.Platform tests. The following project file snippet shows an example.

<PropertyGroup>  ...  <TestingPlatformCommandLineArguments>--minimum-expected-tests 10</TestingPlatformCommandLineArguments></PropertyGroup>

TestingPlatformDotnetTestSupport

TheTestingPlatformDotnetTestSupport property enables testing Microsoft.Testing.Platform apps when using the VSTest mode ofdotnet test.

Note

Don't calldotnet test on a solution that has both VSTest and Microsoft.Testing.Platform projects, as that scenario is not supported.

For more information, seeTesting with 'dotnet test'.

TestingPlatformShowTestsFailure

TheTestingPlatformShowTestsFailure property lets you control whether a single failure or all errors in a failed test are reported when you usedotnet test to run tests. By default, test failures are summarized into a.log file, and a single failure per test project is reported to MSBuild. To show errors per failed test, set this property totrue in your project file.

TestingExtensionsProfile

When you use theMSTest project SDK, theTestingExtensionsProfile property lets you select a profile to use. The following table shows the allowable values.

ValueDescription
DefaultEnables the recommended extensions for this version of MSTest.SDK.
NoneNo extensions are enabled.
AllMicrosoftEnable all extensions shipped by Microsoft (including extensions with a restrictive license).

For more information, seeMicrosoft.Testing.Platform profile.

VSTest–related properties

The following MSBuild properties are documented in this section:

IsTestProject

TheIsTestProject property is set totrue by theMicrosoft.NET.Test.Sdk NuGet package. It signifies whether a project is a VSTest test project so that it's recognized bydotnet test.

Note

If your project specifies theMSTest SDK, you don't need to set this property, as MSTest.Sdk references the Microsoft.NET.Test.Sdk NuGet package.

UseVSTest

Set theUseVSTest property totrue to switch from Microsoft.Testing.Platform to theVSTest runner when using theMSTest project SDK.

MSTest–related properties

The following MSBuild properties are documented in this section:

MSTestAnalysisMode

This property decides which analyzers are enabled at which severity. For more information, seeMSTest code analysis.

Hosting-related properties

The following MSBuild properties are documented in this section:

AppHostDotNetSearch

TheAppHostDotNetSearch property configures howthe native executable produced for an application will search for a .NET installation. This property only impacts the executable produced on publish, not build.

<PropertyGroup>  <AppHostDotNetSearch>Global</AppHostDotNetSearch></PropertyGroup>

The following table lists valid values. You can specify multiple values, separated by semi-colons.

ValueMeaning
AppLocalApp executable's folder
AppRelativePath relative to the app executable as specified byAppHostRelativeDotNet
EnvironmentVariableValue ofDOTNET_ROOT[_<arch>] environment variables
GlobalRegistered anddefault global install locations

This property was introduced in .NET 9.

AppHostRelativeDotNet

TheAppHostRelativeDotNet property allows specifying a relative path for the app executable to look for the .NET installation when it'sconfigured to do so. Setting theAppHostRelativeDotNet property implies thatAppHostDotNetSearch isAppRelative. This property only impacts the executable produced on publish, not build.

<PropertyGroup>  <AppHostRelativeDotNet>./relative/path/to/runtime</AppHostRelativeDotNet></PropertyGroup>

This property was introduced in .NET 9.

EnableComHosting

TheEnableComHosting property indicates that an assembly provides a COM server. Setting theEnableComHosting totrue also implies thatEnableDynamicLoading istrue.

<PropertyGroup>  <EnableComHosting>True</EnableComHosting></PropertyGroup>

For more information, seeExpose .NET components to COM.

EnableDynamicLoading

TheEnableDynamicLoading property indicates that an assembly is a dynamically loaded component. The component could be aCOM library or a non-COM library that can beused from a native host orused as a plugin. Setting this property totrue has the following effects:

  • A.runtimeconfig.json file is generated.
  • RollForward is set toLatestMinor.
  • NuGet references are copied locally.
<PropertyGroup>  <EnableDynamicLoading>true</EnableDynamicLoading></PropertyGroup>

Generated file properties

The following properties concern code in generated files:

DisableImplicitNamespaceImports

TheDisableImplicitNamespaceImports property can be used to disable implicit namespace imports in Visual Basic projects that target .NET 6 or a later version. Implicit namespaces are the default namespaces that are imported globally in a Visual Basic project. Set this property totrue to disable implicit namespace imports.

<PropertyGroup>  <DisableImplicitNamespaceImports>true</DisableImplicitNamespaceImports></PropertyGroup>

ImplicitUsings

TheImplicitUsings property can be used to enable and disable implicitglobal using directives in C# projects that target .NET 6 or a later version and C# 10 or a later version. When the feature is enabled, the .NET SDK addsglobal using directives for a set of default namespaces based on the type of project SDK. Set this property totrue orenable to enable implicitglobal using directives. To disable implicitglobal using directives, remove the property or set it tofalse ordisable.

<PropertyGroup>  <ImplicitUsings>enable</ImplicitUsings></PropertyGroup>

Note

The templates for new C# projects that target .NET 6 or later haveImplicitUsings set toenable by default.

To define an explicitglobal using directive, add aUsing item.

Items

MSBuild items are inputs into the build system. Items are specified according to their type, which is the element name. For example,Compile andReference are twocommon item types. The following additional item types are made available by the .NET SDK:

You can use any of the standarditem attributes, for example,Include andUpdate, on these items. UseInclude to add a new item, and useUpdate to modify an existing item. For example,Update is often used to modify an item that has implicitly been added by the .NET SDK.

AssemblyMetadata

TheAssemblyMetadata item specifies a key-value pairAssemblyMetadataAttribute assembly attribute. TheInclude metadata becomes the key, and theValue metadata becomes the value.

<ItemGroup>  <AssemblyMetadata Include="Serviceable" Value="True" /></ItemGroup>

InternalsVisibleTo

TheInternalsVisibleTo item generates anInternalsVisibleToAttribute assembly attribute for the specified friend assembly.

<ItemGroup>  <InternalsVisibleTo Include="MyProject.Tests" /></ItemGroup>

If the friend assembly is signed, you can specify an optionalKey metadata to specify its full public key. If you don't specifyKey metadata and a$(PublicKey) is available, that key is used. Otherwise, no public key is added to the attribute.

FrameworkReference

TheFrameworkReference item defines a reference to a .NET shared framework.

TheInclude attribute specifies the framework ID.

The project file snippet in the following example references the Microsoft.AspNetCore.App shared framework.

<ItemGroup>  <FrameworkReference Include="Microsoft.AspNetCore.App" /></ItemGroup>

PackageReference

ThePackageReference item defines a reference to a NuGet package.

TheInclude attribute specifies the package ID. TheVersion attribute specifies the version or version range. For information about how to specify a minimum version, maximum version, range, or exact match, seeVersion ranges.

The project file snippet in the following example references theSystem.Runtime package.

<ItemGroup>  <PackageReference Include="System.Runtime" Version="4.3.0" /></ItemGroup>

You can alsocontrol dependency assets using metadata such asPrivateAssets.

<ItemGroup>  <PackageReference Include="Contoso.Utility.UsefulStuff" Version="3.6.0">    <PrivateAssets>all</PrivateAssets>  </PackageReference></ItemGroup>

For more information, seePackage references in project files.

TrimmerRootAssembly

TheTrimmerRootAssembly item lets you exclude an assembly fromtrimming. Trimming is the process of removing unused parts of the runtime from a packaged application. In some cases, trimming might incorrectly remove required references.

The following XML excludes theSystem.Security assembly from trimming.

<ItemGroup>  <TrimmerRootAssembly Include="System.Security" /></ItemGroup>

For more information, seeTrimming options.

Using

TheUsing item lets youglobally include a namespace across your C# project, such that you don't have to add ausing directive for the namespace at the top of your source files. This item is similar to theImport item that can be used for the same purpose in Visual Basic projects. This property is available starting in .NET 6.

<ItemGroup>  <Using Include="My.Awesome.Namespace" /></ItemGroup>

You can also use theUsing item to define globalusing <alias> andusing static <type> directives.

<ItemGroup>  <Using Include="My.Awesome.Namespace" Alias="Awesome" /></ItemGroup>

For example:

  • <Using Include="Microsoft.AspNetCore.Http.Results" Alias="Results" /> emitsglobal using Results = global::Microsoft.AspNetCore.Http.Results;
  • <Using Include="Microsoft.AspNetCore.Http.Results" Static="True" /> emitsglobal using static global::Microsoft.AspNetCore.Http.Results;

For more information, seealiasedusing directives andusing static <type> directives.

Item metadata

In addition to the standardMSBuild item attributes, the following item metadata tags are made available by the .NET SDK:

CopyToPublishDirectory

TheCopyToPublishDirectory metadata on an MSBuild item controls when the item is copied to the publish directory. The following table shows the allowable values.

ValueDescription
PreserveNewestOnly copies the item if it has changed in the source location.
IfDifferentOnly copies the item if it has changed either in the source or target location. This setting is helpful for situations where you need to reset changes that occur after publishing.
AlwaysAlways copies the item.
NeverNever copies the item.

From a performance standpoint,PreserveNewest is preferable because it enables an incremental build. Avoid usingAlways and useIfDifferent instead, which avoids I/O writes with no effect.

<ItemGroup>  <None Update="appsettings.Development.json" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" /></ItemGroup>

LinkBase

For an item that's outside of the project directory and its subdirectories, the publish target uses the item'sLink metadata to determine where to copy the item to.Link also determines how items outside of the project tree are displayed in the Solution Explorer window of Visual Studio.

IfLink is not specified for an item that's outside of the project cone, it defaults to%(LinkBase)\%(RecursiveDir)%(Filename)%(Extension).LinkBase lets you specify a sensible base folder for items outside of the project cone. The folder hierarchy under the base folder is preserved viaRecursiveDir. IfLinkBase is not specified, it's omitted from theLink path.

<ItemGroup>  <Content Include="..\Extras\**\*.cs" LinkBase="Shared"/></ItemGroup>

The following image shows how a file that's included via the previous itemInclude glob displays in Solution Explorer.

Solution Explorer showing item with LinkBase metadata.

See also

Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, seeour contributor guide.

Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo