获取计算机中的硬件信息

时间:2022-09-14 19:23:19

在项目开发过程中,经常会需要读取所在计算机的硬件信息,包括CPU的序列号,主板的序列号,硬盘的序列号,MAC地址,IP地址,用户名,系统类型,计算机名称,操作系统类型,物理内存大小,BIOS内容等。

开发环境:VS2005   .NET2.0

项目工程文件:Computer.zip  

/*****************************************************************/
/* 作者:虞晓杰
 * Emial:fishyxj@sina.com
 * 2011.9.26
 * 功能:用于获取计算机的各种信息,包括CPU的ID,MAC地址,硬盘ID,
 * IP地址登录用户名,计算机名称,系统类型,物理内存,主板的ID,
 * BIOS的ID
 * 
 * 缺陷:当计算机存在虚拟网卡时,无法区分虚拟网卡与真实网卡,因此
 * 读取MAC地址时,会存在不稳定的情况。需要自行处理虚拟网卡MAC的情
 * 况
/*****************************************************************/

using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
using System.Collections;
using System.Net.NetworkInformation;
using Microsoft.Win32;

namespace XFish.Utils
{
    /// <summary>
    /// 计算机信息类
    /// </summary>
    public class Computer
    {
        #region 类内部变量
        private string _CpuID;
        private string _MacAddress;
        private ArrayList _MacAddList;
        private string _DiskID;
        private string _IpAddress;
        private string _LoginUserName;
        private string _ComputerName;
        private string _SystemType;
        private string _TotalPhysicalMemory; //单位:M   
        private string _BaseboardID;
        private string _BiosID;
        private static Computer _instance;
        #endregion

        #region 类属性
        /// <summary>
        /// 获取计算机信息全局实例
        /// </summary>
        /// <returns>Computer实例</returns>
        public static Computer Instance()
        {
            if (_instance == null)
                _instance = new Computer();
            return _instance;
        }
        /// <summary>
        /// 获取CPU的ID
        /// </summary>
        public string CpuID
        {
            get { return _CpuID; }
        }
        /// <summary>
        /// 获取MAC地址
        /// </summary>
        public string MacAddress
        {
            get { return _MacAddress; }
        }
        /// <summary>
        /// 获取计算机中的MAC地址列表,当存在多个网卡时(包括虚拟网卡)
        /// </summary>
        public ArrayList MacAddList
        {
            get { return _MacAddList; }
        }
        /// <summary>
        /// 获取硬盘ID
        /// </summary>
        public string DiskID
        {
            get { return _DiskID; }
        }
        /// <summary>
        /// 获取IP地址(活跃的网卡)
        /// </summary>
        public string IpAddress
        {
            get { return _IpAddress; }
        }
        /// <summary>
        /// 系统登录用户名
        /// </summary>
        public string LoginUserName
        {
            get { return _LoginUserName; }
        }
        /// <summary>
        /// 计算机名称
        /// </summary>
        public string ComputerName
        {
            get { return _ComputerName; }
        }
        /// <summary>
        /// 操作系统类型
        /// </summary>
        public string SystemType
        {
            get { return _SystemType; }
        }
        /// <summary>
        /// 总的物理内存
        /// </summary>
        public string TotalPhysicalMemory
        {
            get { return _TotalPhysicalMemory; }
        }
        /// <summary>
        /// 主板ID
        /// </summary>
        public string BaseboardID
        {
            get { return _BaseboardID; }
        }
        /// <summary>
        /// BIOS的ID
        /// </summary>
        public string BiosID
        {
            get { return _BiosID; }
        }
        #endregion 

        #region 类初始化
        public Computer()
        {
            _CpuID = GetCpuID();
            _MacAddress = GetMacAddress();
            _MacAddList = GetMacAddList();
            _DiskID = GetDiskID();
            _IpAddress = GetIPAddress();
            _LoginUserName = GetUserName();
            _SystemType = GetSystemType();
            _TotalPhysicalMemory = GetTotalPhysicalMemory();
            _ComputerName = GetComputerName();
            _BaseboardID = GetBaseBoardID();
            _BiosID = GetBiosID();
        }
        #endregion

        #region 类方法
        /// <summary>
        /// 获取BIOS序列号
        /// </summary>
        /// <returns></returns>
        private string GetBiosID()
        {
           
            try
            {
                //方法一
                //SelectQuery Query = new SelectQuery("SELECT * FROM Win32_BaseBoard");
                //ManagementObjectSearcher driveID = new ManagementObjectSearcher(Query);
                //ManagementObjectCollection.ManagementObjectEnumerator data = driveID.Get().GetEnumerator();
                //data.MoveNext();
                //ManagementBaseObject board = data.Current;
                //return board.GetPropertyValue("SerialNumber").ToString();
 
                //方法二
                System.Management.ManagementObjectSearcher cmicWmi = new ManagementObjectSearcher("SELECT   *   FROM   Win32_BIOS");
                string biosid = string.Empty;
                ManagementObjectCollection moc = cmicWmi.Get();
                foreach (ManagementObject cmicWmiObj in moc)
                {
                    biosid = cmicWmiObj["SerialNumber"].ToString();
                }
                return biosid;

                //System.Management.ManagementObjectSearcher cmicWmi = new ManagementObjectSearcher("SELECT   *   FROM   Win32_BIOS");
                //string biosid = string.Empty;
                //ManagementObjectCollection moc = cmicWmi.Get();
                //foreach (ManagementObject cmicWmiObj in moc)
                //{
                //    biosid += GetAllInfo(cmicWmiObj);
                //}
                //return biosid;
            }
            catch(Exception ex)
            {
                //throw new Exception("unknow:"+ex.Message);
                return "unknow";
            }
            finally
            {
            }
        }
        /// <summary>
        /// 获取CPU序列号
        /// </summary>
        /// <returns></returns>
        private string GetCpuID()
        {
            try
            {
                //获取CPU序列号代码   
                string cpuInfo = "";//cpu序列号   
                ManagementClass mc = new ManagementClass("Win32_Processor");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
                }
                moc = null;
                mc = null;
                return cpuInfo;



                //string cpuInfo = "";//cpu序列号   
                //ManagementClass mc = new ManagementClass("Win32_Processor");
                //ManagementObjectCollection moc = mc.GetInstances();
                //foreach (ManagementObject mo in moc)
                //{
                //    cpuInfo += GetAllInfo(mo);
                //}
                //moc = null;
                //mc = null;
                //return cpuInfo;
            }
            catch (Exception ex)
            {
                return "unknow";
            }
            finally
            {
            }

        }
        /// <summary>
        /// 获取MAC地址列表
        /// </summary>
        /// <returns></returns>
        private ArrayList GetMacAddList()
        {
            try
            {
                ArrayList maclist = new ArrayList();
                ArrayList warelessMacList = new ArrayList();

                NetworkInterface[] fNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
                foreach (NetworkInterface adapter in fNetworkInterfaces)
                {
                    string fRegistryKey = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\" + adapter.Id + "\\Connection";

                    RegistryKey rk = Registry.LocalMachine.OpenSubKey(fRegistryKey, false);
                    if (rk != null)
                    {
                        // 区分 PnpInstanceID    


                        // 如果前面有 PCI 就是本机的真实网卡   
                        // MediaSubType 为 01 则是常见网卡,02为无线网卡。   
                        string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString();
                        int fMediaSubType = Convert.ToInt32(rk.GetValue("MediaSubType", 0));


                        if (fPnpInstanceID.Length > 3 &&
                        fPnpInstanceID.Substring(0, 3) == "PCI")
                        {
                            string mac = adapter.GetPhysicalAddress().ToString();
                            mac = GetMacStr(mac);
                            maclist.Add(mac);
                        }
                        else if (fMediaSubType == 1)
                            continue;
                        else if (fMediaSubType == 2)
                        {
                            string mac = adapter.GetPhysicalAddress().ToString();
                            mac = GetMacStr(mac);
                            warelessMacList.Add(mac);
                        }
                    }
                }
                maclist.AddRange(warelessMacList);
                return maclist;
            }
            catch
            {
                try
                {
                    ArrayList maclist = new ArrayList();
                    ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                    ManagementObjectCollection moc = mc.GetInstances();
                    foreach (ManagementObject mo in moc)
                    {
                        if (mo["MacAddress"] != null)
                        {
                            string mac = mo["MacAddress"].ToString();
                            maclist.Add(mac);
                        }
                    }
                    moc = null;
                    mc = null;
                    return maclist;
                }
                catch
                {
                    return null;
                }
            }
        }
        /// <summary>
        /// 获取MAC地址
        /// </summary>
        /// <returns></returns>
        private string GetMacAddress()
        {
            try
            {
                string warelessMac = string.Empty;
                string mac = string.Empty;

                NetworkInterface[] fNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
                foreach (NetworkInterface adapter in fNetworkInterfaces)
                {
                    string fRegistryKey = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\" + adapter.Id + "\\Connection";

                    RegistryKey rk = Registry.LocalMachine.OpenSubKey(fRegistryKey, false);
                    if (rk != null)
                    {
                        // 区分 PnpInstanceID    


                        // 如果前面有 PCI 就是本机的真实网卡   
                        // MediaSubType 为 01 则是常见网卡,02为无线网卡。   
                        string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString();
                        int fMediaSubType = Convert.ToInt32(rk.GetValue("MediaSubType", 0));


                        if (fPnpInstanceID.Length > 3 &&
                        fPnpInstanceID.Substring(0, 3) == "PCI")
                        {
                            mac = adapter.GetPhysicalAddress().ToString();
                            break;
                        }
                        else if (fMediaSubType == 1)
                            continue;
                        else if (fMediaSubType == 2)
                            warelessMac = adapter.GetPhysicalAddress().ToString();
                    } 
                }
                if (!mac.Equals(string.Empty))
                    return GetMacStr(mac);
                else if (!warelessMac.Equals(string.Empty))
                    return GetMacStr(warelessMac);
                else
                    return "unknow";
            }
            catch (Exception ex)
            {
                return "unknow";
            }
            finally
            {
            }

        }
        /// <summary>
        /// 获取MAC地址
        /// </summary>
        /// <param name="mac"></param>
        /// <returns></returns>
        private string GetMacStr(string mac)
        {
            string newmac = string.Empty;
            newmac = mac.Substring(0, 2);
            mac = mac.Substring(2, mac.Length - 2);
            while (!mac.Equals(string.Empty))
            {
                newmac += ":";
                newmac += mac.Substring(0, 2);
                mac = mac.Substring(2, mac.Length - 2);
            }
            return newmac;
        }
        /// <summary>
        /// 获取IP地址
        /// </summary>
        /// <returns></returns>
        private string GetIPAddress()
        {
            try
            {
                //获取IP地址   
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"] == true)
                    {
                        //st=mo["IpAddress"].ToString();   
                        System.Array ar;
                        ar = (System.Array)(mo.Properties["IpAddress"].Value);
                        st = ar.GetValue(0).ToString();
                        break;
                    }
                }
                moc = null;
                mc = null;
                return st;
            }
            catch (Exception ex)
            {
                return "unknow";
            }
        }

        /// <summary>
        /// 获取硬盘的序列号
        /// </summary>
        /// <returns></returns>
        private string GetDiskID()
        {
            try
            {
                //方法一
                //ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
                //String strHardDiskID = null;
                //foreach (ManagementObject mo in searcher.Get())
                //{
                //    strHardDiskID = mo["SerialNumber"].ToString().Trim();
                //    break;
                //}
                //return strHardDiskID; 


                //方法二
                //System.Management.ManagementObjectSearcher cmicWmi = new ManagementObjectSearcher("SELECT   *   FROM   Win32_DiskDrive");
                //string diskid = string.Empty;
                //foreach (ManagementObject cmicWmiObj in cmicWmi.Get())
                //{
                //    diskid = cmicWmiObj["signature"].ToString();
                //}
                //return diskid;

                
 
                //方法三   
                //String HDid = "";
                //ManagementClass mc = new ManagementClass("Win32_DiskDrive");
                //ManagementObjectCollection moc = mc.GetInstances();
                //foreach (ManagementObject mo in moc)
                //{
                //    HDid = (string)mo.Properties["model"].Value;
                //}
                //moc = null;
                //mc = null;
                //return HDid;

                //方法四
                System.Management.ManagementObjectSearcher cmicWmi = new ManagementObjectSearcher("SELECT   *   FROM   Win32_DiskDrive");
                string tmp = string.Empty;
                foreach (ManagementObject cmicWmiObj in cmicWmi.Get())
                {
                    bool isSyspan = false;
                    System.Management.PropertyDataCollection pdc = cmicWmiObj.Properties;
                    string info = string.Empty;
                    foreach (PropertyData pd in pdc)
                    {
                        if (pd.Name.Equals("Name"))
                        {
                            if (pd.Value.Equals("\\\\.\\PHYSICALDRIVE0"))
                            {
                                isSyspan = true;
                            }
                        }
                        if (isSyspan)
                        {
                            if (pd.Name.Equals("PNPDeviceID"))
                            {
                                tmp += pd.Value;
                            }
                            else if (pd.Name.Equals("Signature"))
                            {
                                tmp += pd.Value;
                                break;
                            }
                        }
                    }
                }
                return tmp;
                
            }
            catch (Exception ex)
            {
                return "unknow";
            }
            finally
            {
            }

        }

        /// <summary>   
        /// 操作系统的登录用户名   
        /// </summary>   
        /// <returns></returns>   
        private string GetUserName()
        {
            try
            {
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {

                    st = mo["UserName"].ToString();

                }
                moc = null;
                mc = null;
                return st;
            }
            catch (Exception ex)
            {
                return "unknow";
            }
            finally
            {
            }

        }


        /// <summary>   
        /// 获取计算机操作系统类型  
        /// </summary>   
        /// <returns></returns>   
        private string GetSystemType()
        {
            try
            {
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {

                    st = mo["SystemType"].ToString();

                }
                moc = null;
                mc = null;
                return st;
            }
            catch (Exception ex)
            {
                return "unknow";
            }
            finally
            {
            }

        }

        /// <summary>   
        /// 获取计算机物理内存   
        /// </summary>   
        /// <returns></returns>   
        private string GetTotalPhysicalMemory()
        {
            try
            {

                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {

                    st = mo["TotalPhysicalMemory"].ToString();

                }
                moc = null;
                mc = null;
                return st;
            }
            catch (Exception ex)
            {
                return "unknow";
            }
            finally
            {
            }
        }
        /// <summary>
        /// 获取主板的ID
        /// </summary>
        /// <returns></returns>
        private string GetBaseBoardID()
        {
            try
            {
                //string strbNumber = string.Empty;
                //ManagementObjectSearcher mos = new ManagementObjectSearcher("select * from Win32_baseboard");
                //foreach (ManagementObject mo in mos.Get())
                //{
                //    strbNumber = mo["SerialNumber"].ToString();
                //    break;
                //}
                //return strbNumber;
                ManagementClass mc = new ManagementClass("WIN32_BaseBoard");
                ManagementObjectCollection moc = mc.GetInstances();
                string SerialNumber = "";
                foreach (ManagementObject mo in moc)
                {
                    SerialNumber = mo["SerialNumber"].ToString();
                    break;
                }
                return SerialNumber;



                //ManagementClass mc = new ManagementClass("WIN32_BaseBoard");
                //ManagementObjectCollection moc = mc.GetInstances();
                //string SerialNumber = "";
                //foreach (ManagementObject mo in moc)
                //{
                //    SerialNumber = GetAllInfo(mo);
                //}
                //return SerialNumber;
            }
            catch (Exception ex)
            {
                return "unknow";
            }
            finally
            {
            }
        }
        /// <summary>
        /// 获取计算机名称
        /// </summary>
        /// <returns></returns>
        private string GetComputerName()
        {
            try
            {
                return System.Environment.GetEnvironmentVariable("ComputerName");
            }
            catch(Exception ex)
            {
                return "unknow";
            }
            finally
            {
            }
        }

        #endregion
    }
}