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

时间:2014-06-18 06:52:59

标签: c#

工作但崩溃很奇怪,但是硬件状态会打印在控制台窗口中,但是当我运行它时我的应用程序崩溃了。我在表格的负载上有它。 错误说:对象引用未设置为对象的实例

以下是代码:

//硬件检查

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

1 个答案:

答案 0 :(得分:0)

因此,在处理管理对象时,您的问题是所有属性都可以返回null,您需要始终考虑到此问题以及其他一些问题:

  • 搜索者不是设备列表,也不会包含设备列表,因此您不应将其称为设备列表。
  • 您不需要检查搜索者的值,因为我们所做的只是初始化课程,如果没有例外,它就不会失败。
  • 您需要通过处置管理对象来清理自己。

由于NameStatus属性都是字符串,因此您可以在不调用.ToString()的情况下强制转换它们,并使用?? string.Empty替换null个值一个空字符串。

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