Search code examples
c#wmiwmi-query

retrieving WMI query information in uint16 format c#


I've been trying to retrieve information about remote computers in our network via a WMI query. This works fine for all the info I need, I just don't seem to get the UserFriendlyName from the WmiMonitorID class. As this value is stored as a uint16.

The code below returns System.UInt16[]

But I would like to get some readable information.

This is the method I use to retrieve the information:

GetDirectWmiQuery("UserFiendlyName", "WmiMonitorID");
public static string GetDirectWmiQuery(string item, string table)
{
    string result = string.Empty;

    ManagementScope scope;
    scope = new ManagementScope($"\\\\{Var.hostnm}\\root\\WMI");
    scope.Connect();

    ObjectQuery query = new ObjectQuery($"Select {item} FROM {table}");

    ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
    ManagementObjectCollection queryCollection = searcher.Get();

    foreach (ManagementObject m in queryCollection)
    {
        result += m[item].ToString();
    }  
    return result;
}

Solution

  • Translated to C# based on the excellent answer from Jimi,

    The returned array needs to be converted to a string, to become human-eye-friendly. The UInt16 byte array can be converted with Convert.ToByte(UInt16), then tranformed into string with Encoding.GetString().

    foreach (ManagementObject m in queryCollection)
    {
        var data = (ushort[])m[item];
        var monitorID = Encoding.UTF8.GetString((data).Select(Convert.ToByte).ToArray());
    
        result+= monitorID + "\n";
    }