Xamarin Mac - 以编程方式获取系统信息

Xamarin Mac - Get System Information Programmatically

我正在尝试以编程方式获取 Xamarin Mac 中的基本系统信息。

我需要的信息是:

等等。我检查了几篇文章,但在很多情况下,我得到的所有信息都是 OS 相关,而不是硬件相关。

例如: https://forums.xamarin.com/discussion/21835/get-system-information

eg: NSDictionary setting = NSDictionary.FromFile ("/System/Library/CoreServices/SystemVersion.plist");  
string os_version_string = (NSString)setting.ValueForKey ((NSString)"ProductVersion");

提前致谢

您可以通过查询 sysctl 获得大部分信息。但是,Darwin class 中并未公开,因此您需要自己做一些 DllImport

[DllImport(Constants.SystemLibrary)]
internal static extern int sysctlbyname(
    [MarshalAs(UnmanagedType.LPStr)] string property,
    IntPtr output,
    IntPtr oldLen,
    IntPtr newp,
    uint newlen);

然后您可以通过以下方式获取值:

public static string GetSystemProperty(string property)
{
    var pLen = Marshal.AllocHGlobal(sizeof(int));
    sysctlbyname(property, IntPtr.Zero, pLen, IntPtr.Zero, 0);
    var length = Marshal.ReadInt32(pLen);
    var pStr = Marshal.AllocHGlobal(length);
    sysctlbyname(property, pStr, pLen, IntPtr.Zero, 0);
    return Marshal.PtrToStringAnsi(pStr);
 }

您可以在命令行中通过 运行 sysctl -a 列出计算机上的所有密钥,以确定要查询的内容。所以对于你要找的信息你想做:

var cpu = GetSystemProperty("machdep.cpu.brand_string");
var ram = GetSystemProperty("hw.memsize");
var macModel = GetSystemProperty("hw.model");
var osVersion = GetSystemProperty("kern.osrelease");
var hostName = GetSystemProperty("kern.hostname");

您可以通过以下方式获取屏幕信息:

var screenSize = $"{NSScreen.MainScreen.Frame.Width}x{NSScreen.MainScreen.Frame.Height}";

编辑:

您可以通过查询IOKit IOPlatformExpertDevice获取设备序列号。此代码也适用于 iOS:

public static class DeviceSerial
{
    [DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
    private static extern uint IOServiceGetMatchingService(uint masterPort, IntPtr matching);

    [DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
    private static extern IntPtr IOServiceMatching(string s);

    [DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
    private static extern IntPtr IORegistryEntryCreateCFProperty(uint entry, IntPtr key, IntPtr allocator, uint options);

    [DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
    private static extern int IOObjectRelease(uint o);

    public static string GetSerial()
    {
        string serial = string.Empty;
        uint platformExpert = IOServiceGetMatchingService(0, IOServiceMatching("IOPlatformExpertDevice"));
        if (platformExpert != 0)
        {
            NSString key = (NSString)"IOPlatformSerialNumber";
            IntPtr serialNumber = IORegistryEntryCreateCFProperty(platformExpert, key.Handle, IntPtr.Zero, 0);
            if (serialNumber != IntPtr.Zero)
            {
                serial = NSString.FromHandle(serialNumber);
            }
            IOObjectRelease(platformExpert);
        }
        return serial;
    }
}

然后您可以通过以下方式获取序列号:

var serial = DeviceSerial.GetSerial();