C# 获取电脑硬件信息

引入 System.Management.dll

            //获取所有硬盘序列号
            ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
            ManagementObjectCollection disks = diskClass.GetInstances();
            ManagementObjectCollection.ManagementObjectEnumerator disksEnumerator = disks.GetEnumerator();
            while (disksEnumerator.MoveNext())
            {
                ManagementObject disk = (ManagementObject)disksEnumerator.Current;
                Console.WriteLine("Disk found: " + disk["deviceid"] + "序列号:" + disk.Properties["VolumeSerialNumber"].Value.ToString());
            }

            //获取本机MAC地址
            string strMac = string.Empty;

            diskClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = diskClass.GetInstances();

            foreach (ManagementObject mo in moc)
            {
                if ((bool)mo["IPEnabled"] == true)
                {
                    strMac = mo["MacAddress"].ToString();
                }
            }

            Console.WriteLine("MAC地址:" + strMac);

            double capacity = 0;//总物理内存
            double available = 0;//可用物理内存

            ManagementClass cimobject1 = new ManagementClass("Win32_PhysicalMemory");
            ManagementObjectCollection moc1 = cimobject1.GetInstances();
            foreach (ManagementObject mo1 in moc1)
            {
               capacity += ((Math.Round(Int64.Parse(mo1.Properties["Capacity"].Value.ToString()) / 1024 / 1024 / 1024.0, 1)));
            }

            moc1.Dispose();
            cimobject1.Dispose();

            //获取内存可用大小
            ManagementClass cimobject2 = new ManagementClass("Win32_PerfFormattedData_PerfOS_Memory");
            ManagementObjectCollection moc2 = cimobject2.GetInstances();
            foreach (ManagementObject mo2 in moc2)
            {
                available += ((Math.Round(Int64.Parse(mo2.Properties["AvailableMBytes"].Value.ToString()) / 1024.0, 1)));

            }
            moc2.Dispose();
            cimobject2.Dispose();

            double MemoryUsed = (Math.Round((capacity - available) / capacity * 100, 0));//使用率

            Console.WriteLine("总物理内存:" + capacity + ",可用物理内存:" + available + ",使用率:" + MemoryUsed);

 //取CPU编号
            ManagementClass mc = new ManagementClass("Win32_Processor");
            ManagementObjectCollection moc1 = mc.GetInstances();

            string strCpuID = null;

            foreach (ManagementObject mo in moc1)
            {
                strCpuID = mo.Properties["ProcessorId"].Value.ToString();
                break;
            }

            Console.WriteLine("CPU序列号:" + strCpuID);


你可能感兴趣的:(C#,c#,开发语言,后端)