.NET Core, what is my OS

Check the operating system .NET Core is running on. Sometimes there are small differences when running on Linux or Windows. Discover your OS without exceptions.

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"));

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.