What is the best way to test at runtime whether .NET Core application is running on Windows or Linux?

  • 8 months ago
Comment

ChatGPT
1 / 1

You can use the System.Runtime.InteropServices namespace to determine the operating system your .NET Core application is running on. Specifically, you can use the RuntimeInformation.IsOSPlatform method to check the current operating system platform.

Here's an example of how you can use this in your .NET Core application:

csharp
using System;
using System.Runtime.InteropServices;

class Program
{
static void Main()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Console.WriteLine("Running on Windows");
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Console.WriteLine("Running on Linux");
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Console.WriteLine("Running on macOS");
}
else
{
Console.WriteLine("Running on an unknown operating system");
}
}
}

In this example, the RuntimeInformation.IsOSPlatform method is used to check the current operating system platform. You can replace the Console.WriteLine calls with whatever logic you need to execute based on the operating system.

Remember that this approach requires .NET Core 2.0 or later. If you're using an older version, you might need to use different methods or libraries to achieve the same result.