Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
760 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...