【问题标题】:retrieving WMI query information in uint16 format c#以 uint16 格式检索 WMI 查询信息 c#
【发布时间】:2021-01-26 16:35:58
【问题描述】:

我一直在尝试通过 WMI 查询检索有关我们网络中远程计算机的信息。这适用于我需要的所有信息,我只是似乎没有从 WmiMonitorID 类中获取 UserFriendlyName 。因为此值存储为 uint16。

下面的代码返回System.UInt16[]

但我想获得一些可读的信息。

这是我用来检索信息的方法:

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

【问题讨论】:

  • 这能回答你的问题吗? WmiMonitorID - Converting the results to ASCII
  • 感谢您的建议,但该问题与 Visual Basic 中的相同问题有关。而且我不知道如何将该代码翻译成 C#
  • 看答案,第一句话就知道方法和使用方法了。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().
  • 非常感谢,我只需要将 UInt16 字节数组转换为字节,然后将字节转换为字符串。我一定能解决这个问题!

标签: c# wmi wmi-query


【解决方案1】:

根据Jimi的优秀answer翻译成C#,

需要将返回的数组转换为字符串,以便人眼友好。 UInt16 字节数组可以用 Convert.ToByte(UInt16) 转换,然后用 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";
}

【讨论】:

  • 非常感谢,我在 (ushort[])m[item] 上确实收到了错误,但是已经很晚了,我可能在某处做错了什么。我已经在这个问题上停留了三天,所以我明天会毫不犹豫地回来更新。但无论如何,非常感谢你的努力,我真的很感激。
  • 非常感谢,我可以在控制台应用程序中使用您的答案中的代码!
  • 很高兴为您提供帮助,如果可以的话,请考虑对链接的原始答案进行投票。
猜你喜欢
  • 1970-01-01
  • 2016-04-19
  • 1970-01-01
  • 2019-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多