There are a few cases where it is very useful to know the OS your .NET Core application is running on. One of those cases is when you need to set a time zone. Each OS does have its own naming of time zones. You can just try and catch the exception and then retry for another OS, however, if you know the OS, then it is far nicer to do this without exception handling.
Setting time zones on Windows and Linux
When your application needs, local time zones and is running on multiple operating systems. Knowing what is running will enable you to set the time zones without try catch statements. A simple sample on how to solve this:
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { _letTimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Europe/Amsterdam"); } else { _letTimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time"); }
IsOSPlatform
The method IsOSPlatform will let you probe what operating system you are running on:
System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
The possible standard values for OSPlatform are Windows, Linux and OSX.
To get the more information on the perating system, version or architecture you can call the System.Runtime.InteropServices.RuntimeInformation. This static class gives you this information.
var osNameAndVersion = System.Runtime.InteropServices.RuntimeInformation.OSDescription; var osArchitecture = System.Runtime.InteropServices.RuntimeInformation.OSArchitecture; var processArchitecture = System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture;
Operating systems that are not supported with the standard Constants
The IsOSPlatform constants are only available for 3 operating systems. .NET Core does run on far more operating systems. To solve this you can use OSPlatform.Create to check for the not out of the box operating system types. To check for FreeBSD you can run the following code:
var isOS = IsOSPlatform(OSPlatform.Create("FreeBSD"));