Windows Compatibility Pack

A little over a year ago Microsoft released the Windows Compatibility Pack for .NET Core that filled in some gaps in .NET Core APIs if your application doesn’t need to run cross-platform. While some of the APIs included in the compatibility pack was added back when support for .NET Standard 2 was released, such as System.Data.SQL client. Some of the APIs will never make it into the .NET Standard because they are Windows only constructs such as registry access.

Since it has been such a long time since the compatibility pack was released I thought this post would be a good reminder. In this post, we will create a new .NET Core application and using the Windows Compatibility Pack to access the registry.

Application Creation

Use the following command from a command prompt to create a new .NET Core console application.

dotnet new console

Use the following command to add a reference to the compatibility pack NuGet package.

dotnet add package Microsoft.Windows.Compatibility

Using the Registry

The following is the full code for the application. This code may not be the best practice, but it does demonstrate the usage of the registry.

class Program { static void Main(string[] args) { var thing = "World"; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { using (var regKey = Registry .CurrentUser .CreateSubKey(@"Software\Testing\Test")) { thing = regKey.GetValue("ThingText")?.ToString() ?? thing; regKey.SetValue("ThingText", "Registry"); } } Console.WriteLine($"Hello {thing}!"); } }

Take special note of the if statement surrounding the registry access as it allows you to check what platform you are running on and vary your implementation, which is very helpful if your application is actually run cross-platform, but you need some slight differences when running on a particular OS.

The application should output “Hellow World!” the first run and “Hello Registry!” the second run.

Wrapping Up

If you were creating a new application it would be best to stay away from platform specific API as much as possible and stick with the APIs defined by the .NET Standard. If you are trying to convert an existing application I could see the compatibility pack speeding your conversion without having to rewrite part of the application that happens to us Windows-based APIs.