3

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?

heresma
  • 293
  • 2
  • 4
  • 14

3 Answers3

7

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

Community
  • 1
  • 1
SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
  • Note that the (currently) accepted answer on that question suggests a method that, as far as I know, would give you the _volume_ serial number (which is easily changed,) not the _drive_ serial number (which is not easily changed.) – reirab Dec 17 '15 at 22:57
3

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);
}
Omid S.
  • 731
  • 7
  • 15
  • Hello the link did not work anymore, do you have the code by any chance? – Simon Mardiné Nov 28 '22 at 07:27
  • I was able to find it from we archive here will add the code to the post too https://web.archive.org/web/20181126114501/http://www.dotnetspark.com/kb/24-get-processor-id-using-c-sharp.aspx – Omid S. Dec 21 '22 at 01:42
0

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.

nobody
  • 19,814
  • 17
  • 56
  • 77