Search code examples
c#winformsvisual-studio-2010hardware-id

Error while fetching Hardware Info in Visual Studio 2010


I have a C# project where I am trying to deploy a protection mechanism by registering a combination of the Hardware IDs.

I am using the ManagementObjectSearcher Class for the same. Here are some of the commands:

ManagementObjectSearcher cpuget = new ManagementObjectSearcher("Select * From Win32_processor");
ManagementObjectSearcher mainboardget = new ManagementObjectSearcher("SELECT * FROM Win32_BaseBoard");
ManagementObjectSearcher biosget = new ManagementObjectSearcher("Select * From Win32_BIOS");

For fetching the IDs I have:

foreach (ManagementObject mo in cpuList)
    {
        cpuid = mo["ProcessorID"].ToString();
    }
foreach (ManagementObject mo in mainboardlist)
    {
        mbid = mo["SerialNumber"].ToString();
    }

This has been working fine. However, *in some machines(I tested on 10 PCs and two were defaulters)* the error message showed up.

Reference not set to Instance of an Object

Why so? Please Help.


Solution

  • The most difficult problems have the silliest of Answers. Period.

    All I had to do was Check for a null component in the management object class.

    foreach (ManagementObject mo in cpuget.Get())
     {
        if (mo["ProcessorID"] != null)
        cpuid = mo.GetPropertyValue("ProcessorID").ToString();
     }
    

    The similar would be for mbid.

    What a dufus? :|

    P.S.: @L.B suggested this. More power to him.