A
A
Alexander2022-01-20 11:31:54
.NET
Alexander, 2022-01-20 11:31:54

How to quickly detect OS (Windows/Linux) in C# .Net 5/6 cross-platform development?

It seems that the task is banal, but somehow I quickly did not find a solution.
Are there any built-in .Net tools to determine under which OS the program is running?
Something other than how to define OperatingSystem.Platform or some separate definition code of your own, but something aimed specifically at cross-platform.

And even better, if there are some (PS ready-made "out of the box") preprocessor directives, so that the OS definition does not appear in the code?
Those. something like:

#if LINUX
string cmd = @"/bin/bash";
#else
string cmd = @"c:\Windows\System32\cmd.exe"
#end

Yes, I know that /bin/bash is a symlink, and writing an absolute path is wrong, but this is just an example.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2022-01-20
@vabka

And even better, if there are some preprocessor directives, so that the OS definition does not appear in the code?

The preprocessor directives are for that and the preprocessor, that they are only checked during compilation, but it is possible.
Option one - RuntimeIdentifier
Option two - declare your property.
If dynamically in the code, then it is possible through OperatingSystem.IsLinux()
Or through System.Runtime.InteropServices.RuntimeInformation.IsOsPlatform

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question