Getting CPU ID on virtual machine

11k views Asked by At

I am trying to use this code:

public string GetCPUId()
{
    string cpuInfo = String.Empty;
    string temp = String.Empty;
    ManagementClass mc = new ManagementClass("Win32_Processor");
    ManagementObjectCollection moc = mc.GetInstances();
    foreach (ManagementObject mo in moc)
    {
        if (cpuInfo == String.Empty)
        {
            cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
        }
    }
    return cpuInfo;
}

To get a hw uid on a XP virtual machine (virtualbox), but I am only getting a messagebox that says:

Object reference not set to an instance of an object.

Is it because it's a virtual machine or what?

3

There are 3 answers

1
SwDevMan81 On BEST ANSWER

Yes, it is because you are running a virtual machine. mo.Properties["ProcessorId"] will return null. See the answers here.

0
nobody On

That should work just fine on a VM. The CPU ID presented by the virtual CPU may or may not match the physical CPU, though.

2
Omid S. On

I've just found a faster solution here : http://www.dotnetspark.com/kb/24-get-processor-id-using-c-sharp.aspx

it works faster than yours.and IT WORKS IN MY VIRTUAL WINDOWS(using VMware Workstation 7.0.0 with WINDOWS XP installed virtually) as both codes use the same library yours should work as well! try including dll file in project output it MIGHT Help.

UPDATE (2022): Since the linked page is not working any more I am pasting the code :

public static string GetProcessorID()
{

    string sProcessorID = "";

    string sQuery = "SELECT ProcessorId FROM Win32_Processor";

    ManagementObjectSearcher oManagementObjectSearcher = new ManagementObjectSearcher(sQuery);

    ManagementObjectCollection oCollection = oManagementObjectSearcher.Get();
    foreach (ManagementObject oManagementObject in oCollection)
    {
        sProcessorID = (string)oManagementObject["ProcessorId"];
    }
    return (sProcessorID);
}