116

How do I determine what platform my C# code is running on? for example whether it is running on Linux or windows so that I can execute different code at runtime.

I have a C# Windows application that I want to build to target Windows and Linux platforms.

So far I have created two 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 conditional statements using the conditional compilation statement, for example,

#if (LINUX)
    ' Do something
#endif

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bobbo
  • 1,593
  • 4
  • 13
  • 13

11 Answers11

177

I found this recommendation on one of Microsoft's blogs:

We recommend you to use RuntimeInformation.IsOSPlatform() for platform checks.

Reference: Announcing the Windows Compatibility Pack for .NET Core

IsOSPlatform() takes an argument of types OSPlatform which has three values by default: Windows, Linux and OSX. It can be used as follow:

if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
  // Do something
}

The API is part of .NET Standard 2.0, and therefore available in .NET Core 2.0 and .NET Framework 4.7.1.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alex Sanséau
  • 8,250
  • 5
  • 20
  • 25
87

[Editor's Note: This answer was applicable before .NET 4.7.1, or before the Windows Compatibility Pack for .NET Core was released. The current best answer is Alex Sanséau's to Stack Overflow question How to check the OS version at runtime, e.g. on Windows or Linux, without using a conditional compilation statement.]

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, introducing yet another value 6 for macOS.

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.

Community
  • 1
  • 1
Martin Buberl
  • 45,844
  • 25
  • 100
  • 144
24

.NET 5+ has the OperatingSystem class, so now you can just:

if (OperatingSystem.IsWindows())
    DoSomething();
Jony Adamit
  • 3,178
  • 35
  • 44
16

There isn't any such method, but you can use this method that checks it conditionally:

    public static OSPlatform GetOperatingSystem()
    {
        if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
        {
            return OSPlatform.OSX;
        }

        if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
        {
            return OSPlatform.Linux;
        }

        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            return OSPlatform.Windows;
        }

        throw new Exception("Cannot determine operating system!");
    }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alper Ebicoglu
  • 8,884
  • 1
  • 49
  • 55
12

Use:

System.Environment.OSVersion
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Andreas Ågren
  • 3,879
  • 24
  • 33
3

You can use System.Environment.OSVersion to check what kind of platform you're on at runtime.

AlG
  • 14,697
  • 4
  • 41
  • 54
Samuel Otter
  • 608
  • 3
  • 7
2

To expand on other answers, in cases where a Linux and Windows implementation of a feature are not compatible (that is, require references to libraries only available for a specific platform), you can also use an interface and have two separate assemblies, one written and compiled on each platform, with a type that implements this interface.

Then, based on the check, use Assembly.Load() to load only the right assembly (and its platform-specific dependency), reflection to find your type in the assembly, and Activator.CreateInstance() to get an instance of the type that you can then work with normally.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
1

Built-in static method: System.Runtime.Serialization.OperatingSystem.IsLinux().

Dixin
  • 61
  • 1
  • 5
0

One more option is to use Process to call a shell script to get the uname, as follows:

Process p = new Process {
  StartInfo = {
    UseShellExecute        = false,
    RedirectStandardOutput = true,
    FileName               = "uname",
    Arguments              = "-s"
  }
};
p.Start();
string uname = p.StandardOutput.ReadToEnd().Trim();

if (uname == "Darwin") {
  // OS X
} else {
  // ...
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zane Claes
  • 14,732
  • 15
  • 74
  • 131
0
OperatingSystem os = new OperatingSystem(System.Environment.OSVersion.Platform, new Version());
Console.WriteLine(os.ToString());
-1

With the help of TimeZoneConverter libraryable to map the google timezone with the windows time zone. This library has support for windows and Linux and most of the systems.

using TimeZoneConverter;
//Convert Google's Time zone Id into Standard Time Zone name using TimeZoneConvertor library's method named 'GetTimeZoneInfo'
Input : Asia/Hong_Kong 
Output : China Standard Time
TimeZoneInfo tz = TZConvert.GetTimeZoneInfo(timeZoneId);