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=======================";
}
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(, );//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(), , (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();
}
}
}
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 = , /* absolute length of a net name */
MAX_LANA = , /* 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 = , /* Number of NAME's BUFFER */
} [StructLayout(LayoutKind.Sequential)]
public struct ADAPTER_STATUS
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = )]
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 = )]
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 = ; 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[] = (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 > )
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[],
adapter.adapt.adapter_address[],
adapter.adapt.adapter_address[],
adapter.adapt.adapter_address[],
adapter.adapt.adapter_address[],
adapter.adapt.adapter_address[]);
}
}
}
catch
{ }
return addr.Replace(' ', '');
}
}
}
//获取硬盘序列号
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指定在哪个处理器上执行,这样才能确保每次得到相同的结果。
C#获取电脑硬件信息(CPU ID、主板ID、硬盘ID、BIOS编号)的更多相关文章
- Java获取电脑硬件信息
package com.szht.gpy.util; import java.applet.Applet; import java.awt.Graphics; import java.io.Buffe ...
- C++ WMI获取系统硬件信息(CPU/DISK/NetWork etc)
官网找到一个例子,根据例子修改下可以获取很多信息 #define _WIN32_DCOM #include <iostream> using namespace std; #include ...
- 检测硬件的批处理命令,检测硬件bat,一键获取电脑硬件信息
警告:运行BAT源码是一种危险的动作,如果你不熟悉,请不要尝试! 批处理语言: 简体中文 授权方式: 免费软件 运行环境: Windows平台 检测硬件批处理命令.一键获取.直接双击就可以查看 @ec ...
- android 获取系统硬件信息
一,首先设置权限访问: <uses-permission android:name="android.permission.READ_PHONE_STATE" /> ...
- DSAPI 获取实时统计信息CPU/内存/硬盘/网络
有时,我们需要获取当前计算机中CPU.内存.硬盘.网络等实时信息,如下图:\ 要实现上述几项信息的获取,通常需要使用Timer控件来间隔获取,以便刷新最新的数据. 本示例中,放一个Timer控件,放一 ...
- 通过wmi获取本地硬件信息的一些疑问。
通过wmi获取本地硬件信息的一些疑问. http://bbs.csdn.net/topics/391017789 http://blog.csdn.net/xcntime/article/detail ...
- 获取显卡硬件信息lspci -vnn | grep VGA -A 12
lspci -vnn | grep VGA -A 12 lshw -C display lshw -c video | grep configuration glxinfo | grep OpenGL ...
- 网络互联技术(2)——前篇—【转载】电脑结构和CPU、内存、硬盘三者之间的关系
原文链接:传送门 详细内容: 电脑结构和CPU.内存.硬盘三者之间的关系 前面提到了,电脑之父——冯·诺伊曼提出了计算机的五大部件:输入设备.输出设备.存储器.运算器和控制器. 我们看一下现在我们电脑 ...
- C#程序中获取电脑硬件配置信息的一种方法
本文介绍获取cpu信息和内存信息的方法,根据本文所举例的代码可以举一反三获取更多信息. 获取cpu名称的方法: public string GetCpuInfo() { ManagementObjec ...
随机推荐
- ReactNative——UI2.组件生命周期
对于习惯了iOS开发的同学,可能会对React Native中组件的生命周期很困惑.在iOS中有一个ViewDidLoad来初始化,那么在RN中,又是在哪里呢? 一.看图分析 在下图中描述了React ...
- C语言基础:常见循环语句 分类: iOS学习 c语言基础 2015-06-10 21:46 13人阅读 评论(0) 收藏
for语句 for( 初始化表达式; 循环判断条件 ;增量表达式); while(条件表达式){ 循环体; } 先判断条件表达式,如果为真就执行循环体,执行完再去判断条件表达式 do{ 循环体; } ...
- MacBook常用软件
本文分享一些我在mac上的常用软件,也为以后重新配置工作环境做一个记录. 其中提到的大多数软件在网上都有丰富教程,所以仅仅简单描述其功能,不再赘述. 通用 ---Typora Markdown写作工具 ...
- 关于前端的margin
margin 边界,元素周围生成额外的空白区.“空白区”通常是指其他元素不能出现且父元素背景可见的区域.——CSS权威指南 我比较喜欢使用“外边距”这个词来解释margin(同理padding可以称之 ...
- win8转win7+真正解决 “安装程序无法定位现有系统分区,也无法创建新的系统分区”的方法
问题情况:win8电脑转win7系统,出现问题:“安装程序无法定位现有系统分区,也无法创建新的系统分区” 第一种:猜测可行的方法: 1.老毛桃U盘启动电脑,进入PE系统后,直接使用Diskgeni ...
- BZOJ3551: [ONTAK2010]Peaks加强版【Kruskal重构树】【主席树】
重要的事情说三遍 不保证图联通 不保证图联通 不保证图联通 那些和我一样认为重构树是点数的童鞋是要GG Description [题目描述]同3545 Input 第一行三个数N,M,Q. 第二行N个 ...
- 51Nod:1085 背包问题
1085 背包问题 基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 收藏 关注 在N件物品取出若干件放在容量为W的背包里,每件物品的体积为W1,W2--Wn(Wi为 ...
- Alternative Thinking 找规律
Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO ...
- (4)socket的基础使用(基于TCP协议的并发编程)
需要实现并发需要依靠socketserver 模块 socketserver模块下有几个功能 def __init__(self, request, client_address, server): ...
- 【java规则引擎】《Drools7.0.0.Final规则引擎教程》第4章 4.1 规则文件
转载至:https://blog.csdn.net/wo541075754/article/details/75150267 一个标准的规则文件的格式为已“.drl”结尾的文本文件,因此可以通过记事本 ...