C#使用ManagementClass获取计算器硬件信息

目前我了解的获取硬件信息主要有三种方式,具体如下:

1、读取注册表。

2、使用系统API。

3、使用ManagementClass。

下面主要说说如果使用ManagementClass类来获取计算机上CPU、内存、硬盘、网卡、显示、声卡等信息。

1、新建Console控制台项目。

2、添加ManagementClass类引用。

C#使用ManagementClass获取计算器硬件信息_第1张图片

3、定义要获取硬件类型枚举,不创建枚举类型也可以,在创建ManagementClass对象时直接传字符串。

public enum WindowsAPIType
        {
            /// 
            /// 内存
            /// 
            Win32_PhysicalMemory,
            /// 
            /// cpu
            /// 
            Win32_Processor,
            /// 
            /// 硬盘
            /// 
            win32_DiskDrive,
            /// 
            /// 电脑型号
            /// 
            Win32_ComputerSystemProduct,
            /// 
            /// 分辨率
            /// 
            Win32_DesktopMonitor,
            /// 
            /// 显卡
            /// 
            Win32_VideoController,
            /// 
            /// 操作系统
            /// 
            Win32_OperatingSystem

        }

4、硬件信息是以键值对形式返回的,所以在定义要获取信息的键值枚举。 

public enum WindowsAPIKeys
        {
            /// 
            /// 名称
            /// 
            Name,
            /// 
            /// 显卡芯片
            /// 
            VideoProcessor,
            /// 
            /// 显存大小
            /// 
            AdapterRAM,
            /// 
            /// 分辨率宽
            /// 
            ScreenWidth,
            /// 
            /// 分辨率高
            /// 
            ScreenHeight,
            /// 
            /// 电脑型号
            /// 
            Version,
            /// 
            /// 硬盘容量
            /// 
            Size,
            /// 
            /// 内存容量
            /// 
            Capacity,
            /// 
            /// cpu核心数
            /// 
            NumberOfCores
        }

5、创建获取硬件信息单例类 

public class Computer
    {
        private static Computer _instance;
        private static readonly object _lock = new object();
        private Computer()
        { }
        public static Computer CreateComputer()
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = new Computer();
                    }
                }
            }
            return _instance;
        }

        

        public string GetMACString()
        {
            ManagementClass mAdapter = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection mo = mAdapter.GetInstances();
            foreach (ManagementBaseObject m in mo)
            {
                if ((bool)m["IpEnabled"] == true)
                {
                    return m["MacAddress"].ToString();
                }
            }
            mo.Dispose();
            return null;
        }


        /// 
        /// 查找cpu的名称,主频, 核心数
        /// 
        /// 
        public Tuple GetCPU()
        {
            Tuple result = null;
            try
            {
                string str = string.Empty;
                ManagementClass mcCPU = new ManagementClass(WindowsAPIType.Win32_Processor.ToString());
                ManagementObjectCollection mocCPU = mcCPU.GetInstances();
                foreach (ManagementObject m in mocCPU)
                {
                    string name = m[WindowsAPIKeys.Name.ToString()].ToString();
                    string[] parts = name.Split('@');
                    result = new Tuple(parts[0].Split('-')[0] + "处理器", parts[1]);
                    break;
                }

            }
            catch
            {

            }
            return result;
        }

        /// 
        /// 获取CPU的个数
        /// 
        /// 
        public int GetCpuCount()
        {
            try
            {
                using (ManagementClass mCpu = new ManagementClass("Win32_Processor"))
                {
                    ManagementObjectCollection cpus = mCpu.GetInstances();
                    return cpus.Count;
                }
            }
            catch
            {
            }
            return -1;
        }


        /// 
        /// 获取CPU的频率 这里之所以使用string类型的数组,主要是因为cpu的多核
        /// 
        /// 
        public string[] GetCpuMHZ()
        {
            ManagementClass mc = new ManagementClass("Win32_Processor");
            ManagementObjectCollection cpus = mc.GetInstances();

            string[] mHz = new string[cpus.Count];
            int c = 0;
            ManagementObjectSearcher mySearch = new ManagementObjectSearcher("select * from Win32_Processor");
            foreach (ManagementObject mo in mySearch.Get())
            {
                mHz[c] = mo.Properties["CurrentClockSpeed"].Value.ToString();
                c++;
            }
            mc.Dispose();
            mySearch.Dispose();
            return mHz;
        }

        /// 
        /// 获取cpu核心数
        /// 
        /// 
        public string GetCPU_Count()
        {
            string str = "查询失败";
            try
            {
                int coreCount = 0;
                foreach (var item in new System.Management.ManagementObjectSearcher("Select * from " +
 WindowsAPIType.Win32_Processor.ToString()).Get())
                {
                    coreCount += int.Parse(item[WindowsAPIKeys.NumberOfCores.ToString()].ToString());
                }
                if (coreCount == 2)
                {
                    return "双核";
                }
                str = coreCount.ToString() + "核";
            }
            catch
            {

            }
            return str;
        }

        /// 
        /// 操作系统类型
        /// 
        ///  
        public string GetSystemType()
        {
            var st = string.Empty;
            var mc = new ManagementClass("Win32_ComputerSystem");
            var moc = mc.GetInstances();
            foreach (var o in moc)
            {
                var mo = (ManagementObject)o;
                st = mo["SystemType"].ToString();
            }
            return st;
        }

        /// 
        /// 获取系统内存大小
        /// 
        /// 内存大小(单位M)
        public string GetPhisicalMemory()
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher();   //用于查询一些如系统信息的管理对象 
            searcher.Query = new SelectQuery(WindowsAPIType.Win32_PhysicalMemory.ToString(), "",
 new string[] { WindowsAPIKeys.Capacity.ToString() });//设置查询条件 
            ManagementObjectCollection collection = searcher.Get();   //获取内存容量 
            ManagementObjectCollection.ManagementObjectEnumerator em = collection.GetEnumerator();

            long capacity = 0;
            while (em.MoveNext())
            {
                ManagementBaseObject baseObj = em.Current;
                if (baseObj.Properties[WindowsAPIKeys.Capacity.ToString()].Value != null)
                {
                    try
                    {
                        capacity += long.Parse(baseObj.Properties[WindowsAPIKeys.Capacity.ToString()].Value.ToString());
                    }
                    catch
                    {
                        return "查询失败";
                    }
                }
            }
            return ToGB((double)capacity, 1024.0);
        }

        ///   
        /// 将字节转换为GB
        ///   
        /// 字节值  
        /// 除数,硬盘除以1000,内存除以1024  
        ///   
        public static string ToGB(double size, double mod)
        {
            String[] units = new String[] { "B", "KB", "MB", "GB", "TB", "PB" };
            int i = 0;
            while (size >= mod)
            {
                size /= mod;
                i++;
            }
            return Math.Round(size) + units[i];
        }

        /// 
        /// 获取硬盘容量
        /// 
        public string GetDiskSize()
        {
            string result = string.Empty;
            StringBuilder sb = new StringBuilder();
            try
            {
                string hdId = string.Empty;
                ManagementClass hardDisk = new ManagementClass(WindowsAPIType.win32_DiskDrive.ToString());
                ManagementObjectCollection hardDiskC = hardDisk.GetInstances();
                foreach (ManagementObject m in hardDiskC)
                {
                    long capacity = Convert.ToInt64(m[WindowsAPIKeys.Size.ToString()].ToString());
                    sb.Append(ToGB(capacity, 1000.0) + "+");
                }
                result = sb.ToString().TrimEnd('+');
            }
            catch
            {

            }
            return result;
        }
        /// 
        /// 电脑型号
        /// 
        public string GetVersion()
        {
            string str = "查询失败";
            try
            {
                string hdId = string.Empty;
                ManagementClass hardDisk = new ManagementClass(WindowsAPIType.Win32_ComputerSystemProduct.ToString());
                ManagementObjectCollection hardDiskC = hardDisk.GetInstances();
                foreach (ManagementObject m in hardDiskC)
                {
                    str = m[WindowsAPIKeys.Version.ToString()].ToString(); break;
                }
            }
            catch
            {

            }
            return str;
        }
        /// 
        /// 获取分辨率
        /// 
        public string GetFenbianlv()
        {
            string result = "1920*1080";
            try
            {
                string hdId = string.Empty;
                ManagementClass hardDisk = new ManagementClass(WindowsAPIType.Win32_DesktopMonitor.ToString());
                ManagementObjectCollection hardDiskC = hardDisk.GetInstances();
                foreach (ManagementObject m in hardDiskC)
                {
                    result = m[WindowsAPIKeys.ScreenWidth.ToString()].ToString() + "*" +
m[WindowsAPIKeys.ScreenHeight.ToString()].ToString();
                    break;
                }
            }
            catch
            {

            }
            return result;
        }
        /// 
        /// 显卡 芯片,显存大小
        /// 
        public Tuple GetVideoController()
        {
            Tuple result = null;
            try
            {

                ManagementClass hardDisk = new ManagementClass(WindowsAPIType.Win32_VideoController.ToString());
                ManagementObjectCollection hardDiskC = hardDisk.GetInstances();
                foreach (ManagementObject m in hardDiskC)
                {
                    foreach (var v in m.Properties)
                    {
                        Console.WriteLine(v.Name + "     " + v.Value);//VideoModeDescription     1920 x 1080 x 4294967296 种颜色
                    }
                    result = new Tuple(m[WindowsAPIKeys.VideoProcessor.ToString()].ToString()
.Replace("Family", ""), ToGB(Convert.ToInt64(m[WindowsAPIKeys.AdapterRAM.ToString()].ToString()), 1024.0));
                    break;
                }
            }
            catch
            {

            }
            return result;
        }

        /// 
        /// 操作系统版本
        /// 
        public string GetOS_Version()
        {
            string str = "Windows 10";
            try
            {
                string hdId = string.Empty;
                ManagementClass hardDisk = new ManagementClass(WindowsAPIType.Win32_OperatingSystem.ToString());
                ManagementObjectCollection hardDiskC = hardDisk.GetInstances();
                foreach (ManagementObject m in hardDiskC)
                {
                    foreach (var v in m.Properties)
                    {
                        Console.WriteLine(v.Name + "         " + v.Value);
                    }
                    str = m[WindowsAPIKeys.Name.ToString()].ToString().Split('|')[0].Replace("Microsoft", "");
                    break;
                }
            }
            catch
            {

            }
            return str;
        }

    }

6、大家可以参考 https://www.cnblogs.com/jephone/博客,查看每种硬件信息Key-Value说明。

c#获取电脑硬件信息参数说明(硬盘篇 Win32_DiskDrive)

c#获取电脑硬件信息参数说明(CPU篇 Win32_Processor)

c#获取电脑硬件信息参数说明(概述)

 

 

你可能感兴趣的:(C#)