.NET Core – Check which OS you’re running in

.NET Core enables you to write cross-platform C# code.

Sometimes you’ll want to do things differently depending on the OS you’re running in. You can use RuntimeInformation.IsOSPlatform() to figure out which OS you’re in. Here’s an example of using this to see if you’re running in Windows:

System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
Code language: C# (cs)

Example – Loading a different native library depending on if you’re in Windows or Linux

One practical example of needing to know which OS you’re in is when you’re integrating with native libraries, and the native libraries have completely different names on the different OS platforms.

For example, let’s say we want to integrate with a native method called Add(int a, int b). In Windows, this exists in wincalc.dll. In Linux, it’s in advancedcalc.so.

To solve this, we’ll need to:

  • Specify an alias in DllImport.
  • Use NativeLibrary.SetDllImportResolver to specify our own native assembly resolver.
  • Check which platform were in using RuntimeInformation.IsOSPlatform(), so we know which native assembly to try to load.
  • Use NativeLibrary.TryLoad() to load the specified native assembly.

The following code does all of that:

using System.Reflection;
using System.Runtime.InteropServices;
class Program
{
	private const string NATIVE_LIB_ALIAS = "NativeCalculatorLib";
	static void Main(string[] args)
	{
		NativeLibrary.SetDllImportResolver(typeof(Program).Assembly, NativeAssemblyResolver);

		int sum = Add(1, 2);

		Console.WriteLine($"1+2={sum}");
	}

	static IntPtr NativeAssemblyResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
	{
		if (libraryName != NATIVE_LIB_ALIAS)
			return IntPtr.Zero;

		IntPtr libHandle = IntPtr.Zero;

		if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
		{
			Console.WriteLine("On Windows, so using wincalc.dll");
			NativeLibrary.TryLoad("wincalc.dll", assembly, searchPath, out libHandle);
			
		}
		else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
		{
			Console.WriteLine("On Linux, so using advancedcalc.dll");
			NativeLibrary.TryLoad("advancedcalc.so", assembly, searchPath, out libHandle);
		}
		return libHandle;
	}

	[DllImport(NATIVE_LIB_ALIAS)]
	public static extern int Add(int a, int b);
}
Code language: C# (cs)

Leave a Comment