Adding CsWinRT nuget breaks using Windows.System namespace

Viewed 880

I've created a .NET 5.0 project, one of the dependencies I have is on this API:

AnalyticsInfo.VersionInfo.DeviceFamily

After installing Microsoft.Windows.SDK.Contracts, I'm able to use this API. Then, I needed to install the Microsoft.Windows.CsWinRT package to resolve this error:

Error   NETSDK1130  Referencing a Windows Metadata component directly when targeting 
.NETCoreApp,Version=v5.0 is not supported. 

Use the C#/WinRT projection tool (https://aka.ms/cswinrt) or a provided projection for this target.

After installing this, I no longer have access to the Windows.System.Profile namespace to call the AnalyticsInfo API:

Error   CS0234  The type or namespace name 'System' does not exist in the namespace 'Windows' (are you missing an assembly reference?)
1 Answers

With .NET 5, built-in support for WinRT APIs in .NET is removed (because it's Windows specific) , so we can't use Microsoft.Windows.SDK.Contracts any more.

The solution as explained here Built-in support for WinRT is removed from .NET is to

Remove references to the Microsoft.Windows.SDK.Contracts package. Instead, specify the version of the Windows APIs that you want to access via the TargetFramework property of the project. For example:

<TargetFramework>net5.0-windows10.0.19041</TargetFramework>

Note with that in place, there's no need to manually add a reference to C#/WinRT (Microsoft.Windows.CsWinRT) it should be done automatically and shown as "Microsoft.Windows.SDK.NET.Ref" in the list of Frameworks Dependencies.

Related