3

I am trying to get the CPU serial number but I cannot do it. I can get board and harddisk but not cpu.

here is my code below. what am I doing wrong?

public static void GetClientComputerInfo()
    {
        HDDSerial = "0";
        BoardSerial = "0";
        CPUSerial = "0";

        try
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_DiskDrive");

            foreach (ManagementObject share in searcher.Get())
            {
                foreach (PropertyData PC in share.Properties)
                {
                    if (PC.Name == "SerialNumber")
                    {
                        HDDSerial = PC.Value.ToString();
                    }

                    if (PC.Name == "SerialNumber")
                    {
                        BoardSerial = PC.Value.ToString();
                    }

                    if (PC.Name == "ProcessorID")
                    {
                        CPUSerial = PC.Value.ToString();
                    }
                }
            }
        }
        catch
        {

        }
    }
Arif YILMAZ
  • 5,754
  • 26
  • 104
  • 189

1 Answers1

8

Try this one

 string cpuInfo = string.Empty;
    ManagementClass mc = new ManagementClass("win32_processor");
    ManagementObjectCollection moc = mc.GetInstances();

    foreach (ManagementObject mo in moc)
    {
         cpuInfo = mo.Properties["processorID"].Value.ToString();
         break;
    }

Code Extracted from here

Community
  • 1
  • 1
naveejr
  • 735
  • 1
  • 15
  • 31
  • 1
    Does this 'break' in the foreach-loop make any sense? – Martin Tausch Aug 15 '14 at 11:32
  • For me ManagementObjectCollection contain 2 values, but both are same. I honestly don't know why it had 2 values. I thought it depend on number of Cores of CPU. foreach is not needed in this case. but if you want to print all the values I put a console output inside the for loop without break. – naveejr Aug 15 '14 at 11:37
  • 2
    Foreach/break will grab the first value if there is more than one, but prevent an index out of range exception if the collection is empty. This might happen if older systems don't supply a value and you're guessing [0] exists. – Tim Jul 17 '15 at 21:21
  • In Virtual Box VM `cpuInfo = mo.Properties["processorID"].Value.ToString();`will throw a `NullReferenceException`. Use `cpuInfo = (string)mo.Properties["processorID"].Value;` to avoid mistakes. – Andrei Krasutski Jul 20 '22 at 06:53