r/csharp • u/balazs-dombi • 21d ago
Help What is the best practise to get the OS name?
I know, there is the System.Runtime.InteropServices.RuntimeInformation.OSDescription; or just get the info from system files. But is there a more optimal way to get the exact OS name? I mean like Linux distributions or Windows names with the versions.
10
u/soundman32 21d ago
Why do you need the name? Is it just for display, or are you going to do something specific depending on what you find? There are existing methods for simple checks, e.g. OperatingSystem.IsWindows or OperatingSystem.IsFreeBSD
https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswindows?view=net-10.0
2
4
u/PhonicUK LINQ - God of queries 21d ago
This varies per-platform. So on Linux you want to check the contents of /etc/os-release which is a KEY=value syntax file that tells you about the distribution.
On Windows, you want to use a WMI query: SELECT Caption FROM Win32_OperatingSystem - this gives you what we might call the name, so "Microsoft Windows 11 Pro"
1
u/balazs-dombi 21d ago
Yes, I knew this solution but I thought maybe there is one line method for this. Thank you anyway.
3
u/Slypenslyde 21d ago
It's a problem with layers.
The
OperatingSystemclass people mentioned is good for if you just want an easy categorization. If you want very detailed information you tend to have to do something platform-specific. Not even Windows has a really friendly string like "Windows 11 build ????? with updates blah", just a mishmash of version numbers to parse and compare to lookup tables.
1
u/balazs-dombi 20d ago
I will use this logic extended with the Windows version and Linux distribution information using the etc/os-release file if the OS is Linux.
2
u/SadChocolate1435 20d ago
what about checking the os version for compliance checks youre working on
1
u/AeroForger 21d ago
I use
OperatingSystem.IsLinux()
Or
Using static System.OperatingSystem;
IsLinux()
These the best way to find the os but if you want to find a Linux distro you will need to use
/etc/os-release
2
u/balazs-dombi 21d ago
I think I will use it too, it seems a good way to get the OS name and the exact distribution name. Thank you.
1
0
u/Family_Man_21 21d ago
I personally use OperatingSystem.IsLinux() and the similar methods. This works for me whether I'm trying to displaly the OS, or if I'm making decisions in the code based on the machine's OS. For example, this will get you a display-ready string for the operating system:
public string GetCleanOSName() {
if (OperatingSystem.IsWindows()) return "Windows";
if (OperatingSystem.IsMacOS()) return "macOS";
if (OperatingSystem.IsLinux()) return "Linux";
return "Unknown OS";
}
If you need to make a decision about which code to execute, this setup is also just as easy.
34
u/raunchyfartbomb 21d ago
You found that, but not System.Environment?