0

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;
}
Krstf
  • 3
  • 2
  • Does this answer your question? [WmiMonitorID - Converting the results to ASCII](https://stackoverflow.com/questions/51666719/wmimonitorid-converting-the-results-to-ascii) – Mat J Jan 26 '21 at 16:40
  • thanks for the suggestion, but that question is about the same issue in Visual Basic. And I don't know how to translate that code to C# – Krstf Jan 26 '21 at 17:01
  • See the answer, you will find the method and how to use it in first sentence.`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().` – Mat J Jan 26 '21 at 17:05
  • thanks a lot, I just need to convert the UInt16 byte array into bytes and then convert the bytes to a string. I'll be able to figure that one out! – Krstf Jan 26 '21 at 17:38

1 Answers1

0

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";
}
Mat J
  • 5,422
  • 6
  • 40
  • 56
  • Thanks a lot, I do get an error on the (ushort[])m[item], but it is getting late and I'm probably doing something wrong somewhere. I've been stuck on this issue for three days, so I will defiantly come back tomorrow with an update . But in any case, thank you so much for your effort, I truly appreciate it. – Krstf Jan 26 '21 at 21:24
  • Thanks a lot, I got it working in a console app with exactly the code in your answer!! – Krstf Jan 27 '21 at 21:57
  • Glad to help, consider an upvote on the linked original answer if you could. – Mat J Jan 28 '21 at 07:11