Bobbo Bobbo - 2 months ago 12
C# Question

How to check the OS version at runtime e.g. windows or linux without using a conditional compilation statement

Does anyone know how to determine what platform your c# code is running on e.g. whether it is running on linux or windows so that I can execute different code at runtime.

I have a c# windows app that I want to build to target windows and linux platforms.

So far I have created 2 project files pointing to the same set of source code files. I then use a conditional compilation statement one of the projects called LINUX.

Where there are difference in the actual code I use coditional statements using the conditional compilation statement, e.g

#if (LINUX)
' do something
#endif


Is there a better way of doing this? I don't really want to have 2 project files.

Thanks in advance.

Answer

You can detect the execution platform using System.Environment.OSVersion.Platform:

public static bool IsLinux
{
    get
    {
        int p = (int) Environment.OSVersion.Platform;
        return (p == 4) || (p == 6) || (p == 128);
    }
}

From the Mono FAQ:

How to detect the execution platform ?

The execution platform can be detected by using the System.Environment.OSVersion.Platform value. However correctly detecting Unix platforms, in every cases, requires a little more work. The first versions of the framework (1.0 and 1.1) didn't include any PlatformID value for Unix, so Mono used the value 128. The newer framework 2.0 added Unix to the PlatformID enum but, sadly, with a different value: 4 and newer versions of .NET distinguished between Unix and MacOS X, introducing yet another value 6 for MacOS X.

This means that in order to detect properly code running on Unix platforms you must check the three values (4, 6 and 128). This ensure that the detection code will work as expected when executed on Mono CLR 1.x runtime and with both Mono and Microsoft CLR 2.x runtimes.