-4

Working but crashing is weird to say, but the hardware status gets printed in the console window but my application crash when i run this. I have it on the load of the form. Error says: Object reference not set to an instance of an object

And here is the code:

// Hardware check

        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);
            }
user3707281
  • 89
  • 1
  • 5
  • On what line? One of your objects will be `null`, I'd imagine its the `GetPropertyValue` calls – Sayse Jun 18 '14 at 06:54
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Patrick Hofman Jun 18 '14 at 06:54
  • a) Check what `GetPropertyValue` returns before calling `ToString()` b) Learn how to debug an application. – L.B Jun 18 '14 at 06:56
  • Seems to be caused by adding the name of the hardware to the string. When i removed that, the application started as normal. I really dont need the name so im fine with that. Thanks for the help. – user3707281 Jun 18 '14 at 07:07

1 Answers1

0

So your problem when working with management objects is that all properties can return null and you need to account for this at all times as well as some other issues:

  • The searcher is not a list of devices nor will it ever contain one so you shouldn't call it deviceList.
  • You don't need to check the searcher for a value as all we're doing is initializing the class, it won't fail without an Exception.
  • You need to clean up after yourself by disposing of the management objects.

Since both Name and Status properties are strings anyway, you can cast them as such without calling .ToString() and use ?? string.Empty to replace null values with an empty string.

// 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);
        }
}
Ashigore
  • 4,468
  • 1
  • 17
  • 35
  • Do you know any way to say, if every device status is OK? Right now i have if ((status == "Degraded") || (status == "Pred Fail")) { label12.Visible = true; label12.ForeColor = System.Drawing.Color.Red; } else { // Its ok } But this retuns that its both OK and not OK. Cause some devices have devices status OK but some are not. Not sure how to make the condition so that if ALL devices have status OK – user3707281 Jun 18 '14 at 08:07