Getting the Running Operating System in C#
Getting the running operating system in C# is not obvious at first. Here is a simple example that will help -
Console.WriteLine("Platform: " + Environment.OSVersion.Platform);
Console.WriteLine("OS Version: " + Environment.OSVersion.VersionString);
Console.WriteLine("OS Description: " + System.Runtime.InteropServices.RuntimeInformation.OSDescription);
if (Environment.OSVersion.Platform == PlatformID.Unix)
{
Console.WriteLine("\nMore info:");
var lines = File.ReadLines("/etc/os-release");
foreach (var line in lines)
{
Console.WriteLine($"\t{line}");
}
}
This will output something like this in Windows -
Platform: Win32NT
OS Version: Microsoft Windows NT 10.0.19045.0
OS Description: Microsoft Windows 10.0.19045
Note how the OS Version and OS Description can differ significantly Linux -
Platform: Unix
OS Version: Unix 5.15.146.1
OS Description: Debian GNU/Linux 12 (bookworm)
More info:
PRETTY_NAME="Debian GNU/Linux 12 (bookworm)"
NAME="Debian GNU/Linux"
VERSION_ID="12"
VERSION="12 (bookworm)"
VERSION_CODENAME=bookworm
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"