C#获取电脑硬件信息(CPU ID、主板ID、硬盘ID、BIOS编号)

最近学习过程中,想到提取系统硬件信息做一些验证,故而对网上提到的利用.NET System.Management类获取硬件信息做了进一步的学习、验证。验证是分别在4台电脑,XP SP3系统中进行,特将验证过程记录于此。

    说明:

电脑1(联想品牌电脑);

电脑2(HP品牌电脑);

电脑3(联想品牌电脑);

电脑4(兼容机);

  • 获取CPU编号:
ManagementClass mc = new ManagementClass("Win32_Processor");  
ManagementObjectCollection moc = mc.GetInstances();  
string strID = null ;    
foreach( ManagementObject mo in moc )    
{    
 strID = mo.Properties["ProcessorId"].Value.ToString();  
 break;   
}              
textBox1.Text +=  "CPU ID:" + strID; 

 

     返回结果:

        电脑1:CPU ID:BFEBFBFF00000F27

        电脑2:CPU ID:BFEBFBFF00000F27

        电脑3:CPU ID:BFEBFBFF00000F29

        电脑4:CPU ID:BFEBFBFF00000F29

  • 获取主板编号:
ManagementClass mc = new ManagementClass("Win32_BaseBoard");  
ManagementObjectCollection moc = mc.GetInstances();  
string strID = null ;    
foreach( ManagementObject mo in moc )    
{    
 strID = mo.Properties["SerialNumber"].Value.ToString();  
 break;   
}              
textBox1.Text +=  "主板 ID:" + strID; 

 

 

      返回结果:

        电脑1:主板 ID:

        电脑2:主板 ID:CN24401483

        电脑3:主板 ID:AZF241001101

        电脑4:主板 ID: 

 

  • 获取硬盘编号:

ManagementClass mc = new ManagementClass("Win32_PhysicalMedia");  
//网上有提到,用Win32_DiskDrive,但是用Win32_DiskDrive获得的硬盘信息中并不包含SerialNumber属性。   
ManagementObjectCollection moc = mc.GetInstances();  
string strID = null ;    
foreach( ManagementObject mo in moc )    
{    
 strID = mo.Properties["SerialNumber"].Value.ToString();  
 break;   
}              
textBox1.Text +=  "硬盘 ID:" + strID;  
            ManagementClass mc = new ManagementClass("Win32_PhysicalMedia");
            //网上有提到,用Win32_DiskDrive,但是用Win32_DiskDrive获得的硬盘信息中并不包含SerialNumber属性。
            ManagementObjectCollection moc = mc.GetInstances();
            string strID = null ;  
            foreach( ManagementObject mo in moc )  
            {  
             strID = mo.Properties["SerialNumber"].Value.ToString();
             break; 
            }            
            textBox1.Text +=  "硬盘 ID:" + strID;

 

 

 

 

      返回结果:

        电脑1:硬盘 ID:4833395344463658202020202020202020202020 

        电脑2:硬盘 ID:WD-WMAJD1092385

        电脑3:硬盘 ID:4a353756354d5939202020202020202020202020

        电脑4:硬盘 ID:0637J2FW508014

  • 获取BIOS编号:

ManagementClass mc = new ManagementClass("Win32_BIOS");  
ManagementObjectCollection moc = mc.GetInstances();  
string strID = null ;    
foreach( ManagementObject mo in moc )    
{    
 strID = mo.Properties["SerialNumber"].Value.ToString();  
 break;   
}              
textBox1.Text +=  "BIOS ID:" + strID; 

 

 

 

 

     返回结果:

        电脑1:BIOS ID:  

        电脑2:BIOS ID:CN24401483

        电脑3:BIOS ID:

        电脑4:BIOS ID:

 

 

 

    总结:

    由以上各步看出,通过Win32_Processor获取CPUID不正确,或者说Win32_Processor字段就不包含CPU编号信息。

    通过Win32_BaseBoard获取主板信息,但不是所有的主板都有编号,或者说不是能获取所有系统主板的编号。

    通过Win32_PhysicalMedia获取硬盘编号应该没有问题。但网上说可以通过Win32_DiskDrive获取,其实所得信息根本不包含SerialNumber。

    通过Win32_BIOS获取BIOS信息,基本和获取主板信息差不多。就是说:不是所有的主板BIOS信息都有编号。

 

    另外,可以将通过以上各字段所得信息输出,逐个查看所有信息 属性和对应的值。代码如下:

ManagementClass mc = new ManagementClass("Win32_Processor");  
ManagementObjectCollection moc = mc.GetInstances();   
foreach( ManagementObject mo in moc )    
{    
 textBox1.Text += "/r/n============CUP信息===========";  
 foreach (PropertyData pd in mo.Properties)  
 {  
     textBox1.Text += "/r/n" + pd.Name + "/t";  
     if (pd.Value != null)  
     {  
         textBox1.Text += pd.Value.ToString();  
     }  
 }  
 textBox1.Text += "/r/n/r/n=======================";  
}   
            ManagementClass mc = new ManagementClass("Win32_Processor");
            ManagementObjectCollection moc = mc.GetInstances(); 
            foreach( ManagementObject mo in moc )  
            {  
             textBox1.Text += "/r/n============CUP信息===========";
             foreach (PropertyData pd in mo.Properties)
             {
                 textBox1.Text += "/r/n" + pd.Name + "/t";
                 if (pd.Value != null)
                 {
                     textBox1.Text += pd.Value.ToString();
                 }
             }
             textBox1.Text += "/r/n/r/n=======================";
            }

 

 

 

 ===============================================

首先要添加对System.Management.dll的引用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using Microsoft.Win32;
using System.Management;
using System.IO;
namespace 哈哈
{
    class DataOperate
    {
        private SqlConnection conn = null;
        public DataOperate(string connStr)
        {
            conn = new SqlConnection();
            conn.ConnectionString = connStr;
        }
        private void ColseConnnection()
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }
        }
        private void OpenConnection()
        {
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
        }
        /// <summary>
        /// 这里是获取cpu的id
        /// </summary>
        /// <returns></returns>
        public string GetProcessID()
        {
            try
            {
                string str = string.Empty;
                ManagementClass mcCpu = new ManagementClass("win32_Processor");
                ManagementObjectCollection mocCpu = mcCpu.GetInstances();
                foreach (ManagementObject m in mocCpu)
                {
                    str = m["Processorid"].ToString().Trim().Substring(0, 8);//BFEBFBFF00000F65
                }
                return str;
            }
            catch (Exception ex)
            {
                return "likeshan";
            }
        }
        /// <summary>
        /// 获取硬盘id
        /// </summary>
        /// <returns></returns>
        public string GetHardDiskID()
        {
            try
            {
                string hdId = string.Empty;
                ManagementClass hardDisk = new ManagementClass("win32_DiskDrive");
                ManagementObjectCollection hardDiskC = hardDisk.GetInstances();
                foreach (ManagementObject m in hardDiskC)
                {
                    //hdId = m["Model"].ToString().Trim();
                    hdId = m.Properties["Model"].Value.ToString();//WDC WD800BB-56JKC0
                }
                return hdId;
            }
            catch
            {
                return "likeshan";
            }
        }
        /// <summary>
        /// 获取网卡地址
        /// </summary>
        /// <returns></returns>
        public string GetNetwordAdapter()
        {
            try
            {
                string MoAddress = string.Empty;
                ManagementClass networkAdapter = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection adapterC = networkAdapter.GetInstances();
                foreach (ManagementObject m in adapterC)
                {
                    if ((bool)m["IPEnabled"] == true)
                    {
                        MoAddress = m["MacAddress"].ToString().Trim();
                        m.Dispose();
                    }
                }
                return MoAddress;
            }
            catch
            {
                return "likeshan";
            }
        }
        public string GetBaseboard()
        {
            try
            {
                ManagementObjectSearcher mos = new ManagementObjectSearcher("select * from Win32_baseboard");
                string serNumber = string.Empty;
                string manufacturer = string.Empty;
                string product = string.Empty;
 
                foreach (ManagementObject m in mos.Get())
                {
                    serNumber = m["SerialNumber"].ToString();//序列号
                    manufacturer = m["Manufacturer"].ToString();//制造商
                    product = m["Product"].ToString();//型号
                }
                return serNumber + " " + manufacturer + " " + product;
            }
            catch
            {
                return "likeshan";
            }
        }
        /// <summary>
        /// 加密算法(利用到了cpuid)
        /// </summary>
        /// <param name="data">要加密的字符串</param>
        /// <returns></returns>
        public string Encode(string data)
        {
            byte[] akey = ASCIIEncoding.ASCII.GetBytes(GetProcessID());
            byte[] aIV = ASCIIEncoding.ASCII.GetBytes(GetProcessID());
            using (DESCryptoServiceProvider CP = new DESCryptoServiceProvider())
            {
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, CP.CreateEncryptor(akey, aIV), CryptoStreamMode.Write);
                StreamWriter sw = new StreamWriter(cs);
                sw.Write(data);
                sw.Flush();
                cs.FlushFinalBlock();
                sw.Flush();
                return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
            }
        }
        /// <summary>
        /// 加密算法(利用cpuid)
        /// </summary>
        /// <param name="data">需要解密的字符串</param>
        /// <returns></returns>
        public string Decode(string data)
        {
            byte[] akey = ASCIIEncoding.ASCII.GetBytes(GetProcessID());
            byte[] aIV = ASCIIEncoding.ASCII.GetBytes(GetProcessID());
            byte[] Enc = null;
            try
            {
                Enc = Convert.FromBase64String(data);
            }
            catch
            {
                return null;
            }
 
            DESCryptoServiceProvider cp = new DESCryptoServiceProvider();
            MemoryStream ms=new MemoryStream(Enc);
            CryptoStream cs = new CryptoStream(ms, cp.CreateDecryptor(akey, aIV), CryptoStreamMode.Read);
            StreamReader reader = new StreamReader(cs);
            return reader.ReadToEnd();
        }
    }
}

 

 ==============================================

 

首先需添加对System.Management的引用。

 

using System.Runtime.InteropServices;   
using System.Management;   
  
namespace Hardware   
{   
    /// <summary>    
    /// HardwareInfo 的摘要说明。    
    /// </summary>    
    public class HardwareInfo   
    {   
        //取机器名     
        public string GetHostName()   
        {   
            return System.Net.Dns.GetHostName();   
        }   
        //取CPU编号    
        public String GetCpuID()   
        {   
            try   
            {   
                ManagementClass mc = new ManagementClass("Win32_Processor");   
                ManagementObjectCollection moc = mc.GetInstances();   
  
                String strCpuID = null;   
                foreach (ManagementObject mo in moc)   
                {   
                    strCpuID = mo.Properties["ProcessorId"].Value.ToString();   
                    break;   
                }   
                return strCpuID;   
            }   
            catch   
            {   
                return "";   
            }   
  
        }//end method    
  
        //取第一块硬盘编号    
        public String GetHardDiskID()   
        {   
            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;   
            }   
            catch   
            {   
                return "";   
            }   
        }//end     
  
        public enum NCBCONST   
        {   
            NCBNAMSZ = 16,      /* absolute length of a net name         */   
            MAX_LANA = 254,      /* lana's in range 0 to MAX_LANA inclusive   */   
            NCBENUM = 0x37,      /* NCB ENUMERATE LANA NUMBERS            */   
            NRC_GOODRET = 0x00,      /* good return                              */   
            NCBRESET = 0x32,      /* NCB RESET                        */   
            NCBASTAT = 0x33,      /* NCB ADAPTER STATUS                  */   
            NUM_NAMEBUF = 30,      /* Number of NAME's BUFFER               */   
        }   
  
        [StructLayout(LayoutKind.Sequential)]   
        public struct ADAPTER_STATUS   
        {   
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]   
            public byte[] adapter_address;   
            public byte rev_major;   
            public byte reserved0;   
            public byte adapter_type;   
            public byte rev_minor;   
            public ushort duration;   
            public ushort frmr_recv;   
            public ushort frmr_xmit;   
            public ushort iframe_recv_err;   
            public ushort xmit_aborts;   
            public uint xmit_success;   
            public uint recv_success;   
            public ushort iframe_xmit_err;   
            public ushort recv_buff_unavail;   
            public ushort t1_timeouts;   
            public ushort ti_timeouts;   
            public uint reserved1;   
            public ushort free_ncbs;   
            public ushort max_cfg_ncbs;   
            public ushort max_ncbs;   
            public ushort xmit_buf_unavail;   
            public ushort max_dgram_size;   
            public ushort pending_sess;   
            public ushort max_cfg_sess;   
            public ushort max_sess;   
            public ushort max_sess_pkt_size;   
            public ushort name_count;   
        }   
  
        [StructLayout(LayoutKind.Sequential)]   
        public struct NAME_BUFFER   
        {   
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.NCBNAMSZ)]   
            public byte[] name;   
            public byte name_num;   
            public byte name_flags;   
        }   
  
        [StructLayout(LayoutKind.Sequential)]   
        public struct NCB   
        {   
            public byte ncb_command;   
            public byte ncb_retcode;   
            public byte ncb_lsn;   
            public byte ncb_num;   
            public IntPtr ncb_buffer;   
            public ushort ncb_length;   
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.NCBNAMSZ)]   
            public byte[] ncb_callname;   
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.NCBNAMSZ)]   
            public byte[] ncb_name;   
            public byte ncb_rto;   
            public byte ncb_sto;   
            public IntPtr ncb_post;   
            public byte ncb_lana_num;   
            public byte ncb_cmd_cplt;   
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]   
            public byte[] ncb_reserve;   
            public IntPtr ncb_event;   
        }   
  
        [StructLayout(LayoutKind.Sequential)]   
        public struct LANA_ENUM   
        {   
            public byte length;   
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.MAX_LANA)]   
            public byte[] lana;   
        }   
  
        [StructLayout(LayoutKind.Auto)]   
        public struct ASTAT   
        {   
            public ADAPTER_STATUS adapt;   
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.NUM_NAMEBUF)]   
            public NAME_BUFFER[] NameBuff;   
        }   
        public class Win32API   
        {   
            [DllImport("NETAPI32.DLL")]   
            public static extern char Netbios(ref NCB ncb);   
        }   
  
        public string GetMacAddress()   
        {   
            string addr = "";   
            try   
            {   
                int cb;   
                ASTAT adapter;   
                NCB Ncb = new NCB();   
                char uRetCode;   
                LANA_ENUM lenum;   
  
                Ncb.ncb_command = (byte)NCBCONST.NCBENUM;   
                cb = Marshal.SizeOf(typeof(LANA_ENUM));   
                Ncb.ncb_buffer = Marshal.AllocHGlobal(cb);   
                Ncb.ncb_length = (ushort)cb;   
                uRetCode = Win32API.Netbios(ref Ncb);   
                lenum = (LANA_ENUM)Marshal.PtrToStructure(Ncb.ncb_buffer, typeof(LANA_ENUM));   
                Marshal.FreeHGlobal(Ncb.ncb_buffer);   
                if (uRetCode != (short)NCBCONST.NRC_GOODRET)   
                    return "";   
  
                for (int i = 0; i < lenum.length; i++)   
                {   
                    Ncb.ncb_command = (byte)NCBCONST.NCBRESET;   
                    Ncb.ncb_lana_num = lenum.lana[i];   
                    uRetCode = Win32API.Netbios(ref Ncb);   
                    if (uRetCode != (short)NCBCONST.NRC_GOODRET)   
                        return "";   
  
                    Ncb.ncb_command = (byte)NCBCONST.NCBASTAT;   
                    Ncb.ncb_lana_num = lenum.lana[i];   
                    Ncb.ncb_callname[0] = (byte)'*';   
                    cb = Marshal.SizeOf(typeof(ADAPTER_STATUS)) + Marshal.SizeOf(typeof(NAME_BUFFER)) * (int)NCBCONST.NUM_NAMEBUF;   
                    Ncb.ncb_buffer = Marshal.AllocHGlobal(cb);   
                    Ncb.ncb_length = (ushort)cb;   
                    uRetCode = Win32API.Netbios(ref Ncb);   
                    adapter.adapt = (ADAPTER_STATUS)Marshal.PtrToStructure(Ncb.ncb_buffer, typeof(ADAPTER_STATUS));   
                    Marshal.FreeHGlobal(Ncb.ncb_buffer);   
  
                    if (uRetCode == (short)NCBCONST.NRC_GOODRET)   
                    {   
                        if (i > 0)   
                            addr += ":";   
                        addr = string.Format("{0,2:X}{1,2:X}{2,2:X}{3,2:X}{4,2:X}{5,2:X}",   
                         adapter.adapt.adapter_address[0],   
                         adapter.adapt.adapter_address[1],   
                         adapter.adapt.adapter_address[2],   
                         adapter.adapt.adapter_address[3],   
                         adapter.adapt.adapter_address[4],   
                         adapter.adapt.adapter_address[5]);   
                    }   
                }   
            }   
            catch   
            { }   
            return addr.Replace(' ', '0');   
        }   
    }   
}  


 

 

使用方法举例:

//获取硬盘序列号    
Hardware.HardwareInfo hardwareInfo = new Hardware.HardwareInfo();   
string hardDiskID = hardwareInfo.GetHardDiskID();   
System.Console.WriteLine(hardDiskID);   
  
//获取CPU序列号    
string cpuID = hardwareInfo.GetCpuID();   
System.Console.WriteLine(cpuID);   
//获取硬盘序列号Hardware.HardwareInfo hardwareInfo = new Hardware.HardwareInfo();string hardDiskID = hardwareInfo.GetHardDiskID();System.Console.WriteLine(hardDiskID);//获取CPU序列号string cpuID = hardwareInfo.GetCpuID();System.Console.WriteLine(cpuID);   

 

==========

 引用楼主的代码:

//定义DLL文件名,此文件路径要加到系统Path中         

private const string _fileDll = @"CPUID_Util.dll";   

//GetCPUID是 dll里面的一个方法        

  private const string _FountionName = @"GetCPUID";        

  [DllImport(_fileDll, EntryPoint = _FountionName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]         

//C#中的申明         

public static extern string  GetCPUID(string id);  


 回复

   //声明一个stringBuilder类型字符串  

StringBuilder strcpu=new StringBuilder();   

//将strcpu带入函数中        

GetCPUID(strcpu); 

//此时的strcpu已经是cpuid了   Console.writeLine(strcpu);

 

 

==================================

 

多核系统中每个处理器的ID是不同的,在哪个处理器上执行得到的就是哪个处理器的ID,获取ID之前可以用SetThreadAffinityMask指定在哪个处理器上执行,这样才能确保每次得到相同的结果。

展开阅读全文