c# -硬件状态检查,工作但崩溃

本文关键字:工作 崩溃 检查 硬件 状态 | 更新日期: 2023-09-27 18:09:01

工作,但崩溃是奇怪的说,但硬件状态打印在控制台窗口,但我的应用程序崩溃时,我运行这个。我把它放在表单的负载上。错误提示:对象引用未设置为对象的实例

代码如下:

//硬件检查

        ManagementObjectSearcher deviceList =
new ManagementObjectSearcher("Select Name, Status from Win32_PnPEntity");
        // Any results? There should be!
        if (deviceList != null)
            // Enumerate the devices
            foreach (ManagementObject device in deviceList.Get())
            {
                // To make the example more simple,
                string name = device.GetPropertyValue("Name").ToString();
                string status = device.GetPropertyValue("Status").ToString();
                // Uncomment these lines and use the "select * query" if you 
                // want a VERY verbose list
                // foreach (PropertyData prop in device.Properties)
                //    Console.WriteLine( "'t" + prop.Name + ": " + prop.Value);
                // More details on the valid properties:
                // 
                Console.WriteLine("Device name: {0}", name);
                Console.WriteLine("'tStatus: {0}", status);
                // Part II, Evaluate the device status.
                bool working = ((status == "OK") || (status == "Degraded")
                    || (status == "Pred Fail"));
                Console.WriteLine("'tWorking?: {0}", working);
            }

c# -硬件状态检查,工作但崩溃

所以你在处理管理对象时的问题是所有属性都可以返回null,你需要在任何时候都考虑到这一点以及其他一些问题:

  • 搜索器不是设备列表,也不会包含设备列表,所以你不应该叫它deviceList。
  • 你不需要检查搜索器的值,因为我们所做的只是初始化类,它不会失败,除非出现异常。
  • 您需要通过处置管理对象来清理您自己。

由于NameStatus属性无论如何都是字符串,您可以在不调用.ToString()的情况下转换它们,并使用?? string.Emptynull值替换为空字符串。

// Hardware check
using (ManagementObjectSearcher deviceSearcher = new ManagementObjectSearcher("Select Name, Status from Win32_PnPEntity"))
using (ManagementObjectCollection devices = deviceSearcher.Get())
{
        // Enumerate the devices
        foreach (ManagementObject device in devices)
        {
            // To make the example more simple,
            string name = (string)device.GetPropertyValue("Name") ?? string.Empty;
            string status = (string)device.GetPropertyValue("Status") ?? string.Empty;
            // Uncomment these lines and use the "select * query" if you 
            // want a VERY verbose list
            // foreach (PropertyData prop in device.Properties)
            //    Console.WriteLine("'t{0}: {1}", prop.Name, prop.Value);
            // More details on the valid properties:
            // 
            Console.WriteLine("Device name: {0}", name);
            Console.WriteLine("'tStatus: {0}", status);
            // Part II, Evaluate the device status.
            bool working = status == "OK" || status == "Degraded" || status == "Pred Fail";
            Console.WriteLine("'tWorking?: {0}", working);
        }
}