Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
When you first create a project, we recommend you create a .NET Standard class library, as it provides compatibility with the widest range of consuming projects. By using .NET Standard, you add cross-platform support to a .NET library by default. However, in some scenarios, you may also need to include code that targets a particular framework. This article shows you how to do that for SDK-style projects.
For SDK-style projects, you can configure support for multiple targets frameworks (TFM) in your project file, then use dotnet pack or msbuild /t:pack to create the package.
Create a project that supports multiple .NET frameworks
Create a new .NET Standard class library either in Visual Studio or use
dotnet new classlib.We recommend that you create a .NET Standard class library for best compatibility.
Edit the .csproj file to support the target frameworks. For example, change
<TargetFramework>netstandard2.0</TargetFramework>to:
<TargetFrameworks>netstandard2.0;net45</TargetFrameworks>Make sure that you change the XML element changed from singular to plural (add the "s" to both the open and close tags).
If you have any code that only works in one TFM, you can use
#if NET45or#if NETSTANDARD2_0to separate TFM-dependent code. (For more information, see How to multitarget.) For example, you can use the following code:public string Platform { get { #if NET45 return ".NET Framework" #elif NETSTANDARD2_0 return ".NET Standard" #else #error This code block does not match csproj TargetFrameworks list #endif } }Add any NuGet metadata you want to the .csproj as MSBuild properties.
For the list of available package metadata and the MSBuild property names, see pack target. Also see Controlling dependency assets.
If you want to separate build-related properties from NuGet metadata, you can use a different
PropertyGroup, or put the NuGet properties in another file and use MSBuild'sImportdirective to include it.Directory.Build.PropsandDirectory.Build.Targetsare also supported starting with MSBuild 15.0.Now, use
dotnet packand the resulting .nupkg targets both .NET Standard 2.0 and .NET Framework 4.5.
Here is the .csproj file that is generated using the preceding steps and .NET Core SDK 2.2.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net45</TargetFrameworks>
<Description>Sample project that targets multiple TFMs</Description>
</PropertyGroup>
</Project>
Multi-targeting with duplicate frameworks
Starting with NuGet 7.6 / .NET SDK 10.0.300, you can use multiple TargetFrameworks values that resolve to the same underlying framework. This enables scenarios like building for multiple runtimes or targeting multiple versions of a host application from a single project.
For details on how this works with restore and pack, see Targeting multiple frameworks.