开发者

Getting CPU ID on virtual machine

开发者 https://www.devze.com 2023-02-13 10:46 出处:网络
I am trying to use this code: public string GetCPUId() { string cpuInfo = String.Empty; string temp = String.Empty;

I am trying to use this code:

public string GetCPUId()
{
    string cpuInfo = String.Empty;
    string temp = String.Empty;
    ManagementClass mc = new ManagementClass("W开发者_高级运维in32_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?


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


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);
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消