简体   繁体   中英

How to get cross-platform system model name with .NET 5?

I'm developing a cross-platform application in C# / NET 5, it will run on both Windows and MacOS. I need to print the "manufacturer model name" of the running system. On Windows, this is more or less what is returned by querying the WMI class Win32_ComputerSystem . For example the "Name" field:

  Caption:  Computer System Product
  Description:  Computer System Product
  IdentifyingNumber:  <hidden>
  Name:  Inspiron 7370  **<--- I need to print this kind of info!**
  UUID:  <hidden>
  Vendor:  Dell Inc.
  Version:  

The software will run also on MacOS, so I need a common way to retrieve, example, "Apple Mac Mini" or similar string. I assume it won't be possible to get it via WMI.

Is there a cross-platform solution? Thanks

I've "solved" by branching between the different OS and without needing to use System.Management package:

public static string GetSystemModelName()
{
    var cmd = new ProcessStartInfo();
    cmd.RedirectStandardError = true;
    cmd.CreateNoWindow = true;
    cmd.UseShellExecute = false;
    cmd.RedirectStandardOutput = true;

    if (System.OperatingSystem.IsWindows())
    {
        cmd.FileName = "CMD.exe";
        cmd.Arguments = "/C wmic csproduct get name | find /v \"Name\"";
    }
    else if (System.OperatingSystem.IsMacOS())
    {
        cmd.FileName = "sh";
        cmd.Arguments = "-c \"sysctl -n hw.model\"";
    }
    else return null;

    try
    {

        var builder = new StringBuilder();
        using (Process process = Process.Start(cmd))
        {
            process.WaitForExit();
            builder.Append(process.StandardOutput.ReadToEnd());
        }

        return builder.ToString().Trim();
    }
    catch (Exception)
    {
        return null;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM