C#读取CPU数量,物理内存容量代码

漂洋过海的鱼 发表于:2018-08-01 17:02 阅读: 331次

可以通过Windows Management Instrumentation (WMI)提供的接口读取所需要的信息,一下是在项目中使用的方法,记录下来以后备用.

读取CPU实时状态方法

private static UInt32 CountPhysicalProcessors() 
    { 
         ManagementObjectSearcher objects = new ManagementObjectSearcher( 
            “SELECT * FROM Win32_ComputerSystem”); 
         ManagementObjectCollection coll = objects.Get(); 
         foreach(ManagementObject obj in coll) 
        { 
            return (UInt32)obj[“NumberOfProcessors”]; 
        } 
        return 0; 
    }

读取物理内存容量方法

private static UInt64 CountPhysicalMemory() 
    { 
       ManagementObjectSearcher objects =new ManagementObjectSearcher( 
          “SELECT * FROM Win32_PhysicalMemory”); 
       ManagementObjectCollection coll = objects.Get(); 
       UInt64 total = 0; 
       foreach (ManagementObject obj in coll) 
       { 
           total += (UInt64)obj[“Capacity”]; 
        } 
        return total; 
    }
酷码派 [KuMaPai.COM] - 陕ICP备案证 18010024号-2