Skip to main content

C# helper class to detect the current operating platform/os.

namespace DotnetCommon.Utils
{
    using System;
    using System.Runtime.InteropServices;
    using System.Text;

    public static class Platform
    {
        static Platform()
        {
            var name = GetUname();

            IsWindows = name == string.Empty;
            IsMacOs = string.Equals(name, "Darwin", StringComparison.Ordinal);
            IsLinux = !IsWindows && !IsMacOs;
        }

        public static bool IsWindows { get; }
        public static bool IsMacOs { get; }
        public static bool IsLinux { get; }

        [DllImport("libc")]
        private static extern int uname(StringBuilder buf);

        private static string GetUname()
        {
            var buffer = new StringBuilder(8192);

            try
            {
                if (uname(buffer) == 0)
                {
                    return buffer.ToString();
                }
            }
            catch
            {
                // swallow...
            }

            return string.Empty;
        }
    }
}