Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
762 views
in Technique[技术] by (71.8m points)

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;
}
question from:https://stackoverflow.com/questions/65905351/retrieving-wmi-query-information-in-uint16-format-c-sharp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 + "
";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...