Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect properly Windows, Linux & Mac operating systems

Tags:

I could not found anything really efficient to detect correctly what platform (Windows / Linux / Mac) my C# progrma was running on, especially on Mac which returns Unix and can't hardly be differenciated with Linux platforms !

So I made something less theoretical, and more practical, based on specificities of Mac.

I'm posting the working code as an answer. Please, comment if it works well for you too / can be improved.

Thanks !

Response :

Here is the working code !

    public enum Platform
    {
        Windows,
        Linux,
        Mac
    }

    public static Platform RunningPlatform()
    {
        switch (Environment.OSVersion.Platform)
        {
            case PlatformID.Unix:
                // Well, there are chances MacOSX is reported as Unix instead of MacOSX.
                // Instead of platform check, we'll do a feature checks (Mac specific root folders)
                if (Directory.Exists("/Applications")
                    & Directory.Exists("/System")
                    & Directory.Exists("/Users")
                    & Directory.Exists("/Volumes"))
                    return Platform.Mac;
                else
                    return Platform.Linux;

            case PlatformID.MacOSX:
                return Platform.Mac;

            default:
                return Platform.Windows;
        }
    }
like image 994
OlivierB Avatar asked Apr 13 '12 09:04

OlivierB


2 Answers

Maybe check out the IsRunningOnMac method in the Pinta source:

like image 161
TheNextman Avatar answered Jan 03 '23 00:01

TheNextman


Per the remarks on the Environment.OSVersion Property page:

The Environment.OSVersion property does not provide a reliable way to identify the exact operating system and its version. Therefore, we do not recommend that you use this method. Instead: To identify the operating system platform, use the RuntimeInformation.IsOSPlatform method.

RuntimeInformation.IsOSPlatform worked for what I needed.

if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
    // Your OSX code here.
}
elseif (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
    // Your Linux code here.
}
like image 33
Stev Avatar answered Jan 02 '23 23:01

Stev