C#获取电脑硬件信息,并且教会你如何使用
C#获取电脑硬件信息使用到的参数的链接,等你明白了肯定会用到,所以我把他放在最上面你会用到我的引用命名空间using System.Management;using System;using System.Diagnostics;并且在引用中添加DIY你可以自己获取别的硬件的参数首先你需要看上面的链接,看一下参数,这里我使用硬盘往下看有一个成员或者在右边点击成员可以查看每一个参数的介绍,首先选择你
C#获取电脑硬件信息
一位大佬制作的开源的获取硬件信息的东西。
基于C#,这是链接
GitHub地址:https://github.com/openhardwaremonitor
网站链接:https://openhardwaremonitor.org/
使用到的参数的链接,等你明白了肯定会用到,所以我把他放在最上面
你会用到我的
引用命名空间
using System.Management;
using System;
using System.Diagnostics;
并且在引用中添加
DIY
你可以自己获取别的硬件的参数
首先你需要看上面的链接,看一下参数,这里我使用硬盘
往下看有一个成员或者在右边点击成员可以查看每一个参数的介绍,
首先选择你想查看硬件的硬件类型,
然后你可以在右边开到这个东西的介绍,
在语法里面需有粉色的框框的东西,不需知道是什么东西,当硬件改变的时候,需要把"Select * from ( )"括号中的东西改成对应的就行了。
然后是返回值类型,大多是int类型或是string类型,两个类型的使用方法有很小的不同。然后是参数类型,,如果你要获取一个硬件的其他参数类型可以来这里搜索。
返回值类型为string类型的使用方式
/// <summary>
/// 获取硬件信息String,返回值为string类型
/// </summary>
/// <returns></returns>
public static string GethardwareParameters()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM win32_DiskDrive");//如果要获取别的硬件改"win32_DiskDrive";
string ParameterInformation = "";
foreach (ManagementObject mo in searcher.Get())
{
var b = mo["Caption"].ToString();//如果要获取硬件的其他参数将中括号中的参数"Caption"改为参数名称。
ParameterInformation = b +"\n"+ ParameterInformation;
}
return ParameterInformation;
}
catch
{
return "No hardware parameter information is obtained. Please check whether the parameter return value is correct.";
}
}
返回值类型为int类型
有些返回值可能是错误代码,我暂时没有整明白是怎么回事,或者怎么用。
在"Win32 _ VideoController"中第四个参数是获取显示卡的RAM " uint32 AdapterRAM;" ,我不知道如何计算。
我的电脑使用的显卡是1060 6G版本,得到的返回值是:4293918720
显存是6G,我不知道这个数字如何计算才会等于6。
关于显示器的参数也是在显卡里面获取的。
/// <summary>
/// 获取硬件信息Int,返回值为Int类型
/// </summary>
/// <returns></returns>
public static string GethardwareParameters_Int()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM win32_DiskDrive");//如果要获取别的硬件改"win32_DiskDrive";
string ParameterInformation = "";
foreach (ManagementObject mo in searcher.Get())
{
string SizeStr_B = mo["Size"].ToString();//如果要获取硬件的其他参数将中括号中的参数"Caption"改为参数名称。
//并且数字的话类型最好是long,或者是float ,
//不同的硬件的计算方式不一样,硬盘进制是1000,内存是1024,单位都是字节,这个可以在文档中找到。
long sizeLong_B = long.Parse(SizeStr_B);
float sizeFloat_GB = sizeLong_B / 1000 / 1000 / 1000;
ParameterInformation = "设备的描述是:" + mo["Caption"] + ",设备的参数信息是(这里是获取的是硬盘的容量):" + sizeFloat_GB+"GB。"+"\n"+ ParameterInformation;
}
return ParameterInformation;
}
catch
{
return "Hardware parameter information is not obtained. Please check whether 1. Parameter return value is correct, 2. Hardware Win32 name is correct, 3. Parameter spelling is correct.";
}
}
下面就是一些写好的
获取CPU名称
/// <summary>
/// CPU名称信息
/// </summary>
/// <returns></returns>
public static string GetCpuName()
{
var CPUName = "";
var management = new ManagementObjectSearcher("Select * from Win32_Processor");
foreach (var baseObject in management.Get())
{
var managementObject = (ManagementObject)baseObject;
CPUName = managementObject["Name"].ToString();
}
return CPUName;
}
返回值为: Intel® Core™ i5-8300H CPU @ 2.30GHz
获取CPU的制造厂商
/// <summary>
/// CPU制造厂商
/// </summary>
/// <returns></returns>
public static string GetCpuManufacturer()
{
var CPUMakerStr = "";
var management= new ManagementObjectSearcher("Select * from Win32_Processor");
foreach (var baseObject in management.Get())
{
var managementObject = (ManagementObject)baseObject;
CPUMakerStr = managementObject["Manufacturer"].ToString();
}
return CPUMakerStr;
}
返回值是 :Intel的返回值是这个:GenuineIntel,AMD的暂时不知道。
获取IPV4地址
- 方式1
using System.Net;
using System.Net.Sockets;
/// <summary>
/// 获取IPv4地址
/// </summary>
/// <returns>IP v4地址</returns>
private static string GetIp1()
{
string name = Dns.GetHostName();
IPAddress[] ipadrlist = Dns.GetHostAddresses(name);
foreach (IPAddress ipa in ipadrlist)
{
if (ipa.AddressFamily == AddressFamily.InterNetwork)
{
return ipa.ToString();
}
}
return "IPv4为空";
}
- 方式2
/// <summary>
/// 获取IP地址
/// </summary>
/// <returns></returns>
public static string GetIpAddress()
{
var IPv4Str = "";
var management = new ManagementClass("Win32_NetworkAdapterConfiguration");
var managementObject = management.GetInstances();
foreach (ManagementBaseObject managementBaseObject in managementObject)
{
var management1 = (ManagementObject)managementBaseObject;
if (!(bool)management1["IPEnabled"]) continue;
Array array = (Array)(management1.Properties["IpAddress"].Value);
IPv4Str = array.GetValue(0).ToString();
break;
}
return IPv4Str;
}
- 方式3
using System.Text.RegularExpressions;
using System.Diagnostics;
/// <summary>
/// 获取IP v4地址
/// </summary>
/// <returns>IPv4地址</returns>
/// 使用正则表达式在info中获取ipv4 地址,可以修改正则表达式来获取ipv6地址
private static string GetIPv4()
{
Process cmd = new Process();
cmd.StartInfo.FileName = "ipconfig.exe";//设置程序名
cmd.StartInfo.Arguments = "/all"; //参数
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.CreateNoWindow = true;//不显示窗口(控制台程序是黑屏)
cmd.Start();
string info = cmd.StandardOutput.ReadToEnd();
cmd.WaitForExit();
cmd.Close();
Match m = Regex.Match(info, @"\d+\.\d+\.\d+\.\d+");
var ipString = m.ToString();
return ipString;
}
获取IPV6地址
获取IPV6地址
using System;
using System.Text.RegularExpressions;
using System.Diagnostics;
/// <summary>
/// 获取IPV6地址
/// </summary>
/// <returns></returns>
public static string GetIPV6()
{
Process cmd = new Process();
cmd.StartInfo.FileName = "ipconfig.exe";//设置程序名
cmd.StartInfo.Arguments = "/all"; //参数
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.CreateNoWindow = true;//不显示窗口(控制台程序是黑屏)
cmd.Start();
string info = cmd.StandardOutput.ReadToEnd();
string[] de = new string[info.Length];
cmd.WaitForExit();
cmd.Close();
string patten = (
@"((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:)
{6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:
((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:
((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:
((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:
((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:
((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]
\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?");
Match m = Regex.Match(info, patten);
var ipString = m.ToString();
var v = ipString.Split('(');//获取到的IPV6地址后面会有一个(首选),在这里把他去掉
return v[0];
}
获取主机名称
/// <summary>
/// 获取计算机名
/// </summary>
/// <returns>计算机名称</returns>
public static string GetComputerName()
{
return Environment.MachineName;
}
操作系统类型
/// <summary>
/// 操作系统类型
/// </summary>
/// <returns>操作系统类型</returns>
public static string GetSystemType()
{
var sysTypeStr = "";
ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementBaseObject o in moc)
{
ManagementObject mo = (ManagementObject)o;
sysTypeStr = mo["SystemType"].ToString();
}
return sysTypeStr;
}
win10 家庭版返回值: x64-based PC
内存
- 内存总量,
返回值类型为float,16GB内存会大概是15.875GB
/// <summary>
/// 物理内存的容量
/// </summary>
/// <returns>物理内存,返回值类型为float,16GB内存返回15.875GB</returns>
public static float GetPhysicalMemory()
{
float memoryCount = 0;
var mc = new ManagementClass("Win32_ComputerSystem");
var moc = mc.GetInstances();
foreach (var o in moc)
{
var mo = (ManagementObject)o;
string str = mo["TotalPhysicalMemory"].ToString();//单位为 B
float a = long.Parse(str);
memoryCount = a / 1024 / 1024 / 1024;//单位换成GB
}
return memoryCount;
}
- 内存条的根数
/// <summary>
/// 内存的数量,
/// </summary>
/// <returns>内存条的根数</returns>
public static int MemoryNumberCount()
{
ManagementClass m = new ManagementClass("Win32_PhysicalMemory");//内存条
ManagementObjectCollection mn = m.GetInstances();
int count = mn.Count;
return count;
}
参照
助手查看
控制台
主板制造商
/// <summary>
/// 主板制造厂商
/// </summary>
/// <returns>主板制造商</returns>
public static string GetBoardManufacturer()
{
SelectQuery query = new SelectQuery("Select * from Win32_BaseBoard");
ManagementObjectSearcher mos = new ManagementObjectSearcher(query);
ManagementObjectCollection.ManagementObjectEnumerator data = mos.Get().GetEnumerator();
data.MoveNext();
ManagementBaseObject board = data.Current;
string baseBoradMaker = board.GetPropertyValue("Manufacturer").ToString();
return baseBoradMaker;
}
联想拯救者Y7000返回值为LENOVO
主板编号
联想客服要的主机号
/// <summary>
/// 主板编号
/// </summary>
/// <returns></returns>
public static string GetBoardId()
{
string str = "";
ManagementObjectSearcher mos = new ManagementObjectSearcher("Select * from Win32_BaseBoard");
foreach (var o in mos.Get())
{
ManagementObject mo = (ManagementObject)o;
str = mo["SerialNumber"].ToString();
}
return str;
}
主板型号
只测试过笔记本的,没有试过台式机的。
/// <summary>
/// 主板型号
/// </summary>
/// <returns></returns>
public static string GetBoardType()
{
string str ="";
ManagementObjectSearcher mos = new ManagementObjectSearcher("Select * from Win32_BaseBoard");
foreach (var o in mos.Get())
{
ManagementObject mo = (ManagementObject)o;
str = mo["Product"].ToString();
}
return str;
}
CPU 序列号
/// <summary>
/// CPU序列号
/// </summary>
/// <returns></returns>
private static string GetCPUNO()
{
string CPU_NO = "";//cpu序列号
ManagementClass managementClass = new ManagementClass("Win32_Processor");
ManagementObjectCollection moc = managementClass.GetInstances();
foreach (ManagementObject mo in moc)
{
CPU_NO = mo.Properties["ProcessorId"].Value.ToString();
}
return CPU_NO;
}
GPU数量和型号
/// <summary>
/// 获取GPU名称,型号
/// </summary>
private static string GPUName()
{
string DisplayName = "";
ManagementClass m = new ManagementClass("Win32_VideoController");
ManagementObjectCollection mn = m.GetInstances();
DisplayName = "显卡数量:" + mn.Count.ToString() + " " + "\n";
ManagementObjectSearcher mos = new ManagementObjectSearcher("Select * from Win32_VideoController");//Win32_VideoController 显卡
int count = 0;
foreach (ManagementObject mo in mos.Get())
{
count++;
DisplayName += "第" + count.ToString() + "张显卡名称:" + mo["Name"].ToString() + " " + "\n";
}
mn.Dispose();
m.Dispose();
return DisplayName;
}
获取主硬盘的名称
不一定是C盘所在硬盘的名称
private static string GETDiskName()
{
try
{
string DiskID = "";
ManagementClass mc = new ManagementClass("Win32_DiskDrive");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
DiskID = mo.Properties["Model"].Value.ToString();
}
mc = null;
moc = null;
return DiskID;
}
catch
{
return "Failed to get disk name";
}
finally
{
}
}
获取全部硬盘的名称
/// <summary>
/// 获取全部硬盘的名称
/// </summary>
/// <returns></returns>
public static string GetDiskSerialNumber()
{
//这种模式在插入一个U盘后可能会有不同的结果,如插入我的手机时
var hDid = string.Empty;
var mc = new ManagementClass("Win32_DiskDrive");
var moc = mc.GetInstances();
foreach (var o in moc)
{
var mo = (ManagementObject)o;
hDid = hDid+(string)mo.Properties["Model"].Value+"\n";
}
return hDid;
}
获取硬盘的序列号
/// <summary>
/// 硬盘的序列号
/// </summary>
/// <returns></returns>
public static string GetHardDiskSerialNumber()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM win32_DiskDrive");
string sHardDiskSerialNumber = "";
foreach (ManagementObject mo in searcher.Get())
{
sHardDiskSerialNumber = sHardDiskSerialNumber + mo["SerialNumber"].ToString().Trim() + "\n";
}
return sHardDiskSerialNumber;
}
catch
{
return "The hard disk serial number was not obtained.";
}
}
获取每一个硬盘的容量
/// <summary>
/// 获取每一个硬盘的容量,单位GB
/// </summary>
/// <returns></returns>
public static string GetDiskCapacity()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM win32_DiskDrive");
string HardDriveCapacity = "";
foreach (ManagementObject mo in searcher.Get())
{
long size_B = long.Parse(mo["Size"].ToString());//
float sizeGB = size_B / 1000 / 1000 / 1000;
HardDriveCapacity = sizeGB.ToString() + "\n" + HardDriveCapacity;
}
return HardDriveCapacity;
}
catch
{
return "Failed to get the capacity of each disk.";
}
}
硬盘的一些参数
微软的官方链接
将foreach中中括号中的属性换成下面的参数名称可以得到对应的数据
[Dynamic, Provider("CIMWin32"), UUID("{8502C4B2-5FBB-11D2-AAC1-006008C78BC7}"), AMENDMENT]
class Win32_DiskDrive : CIM_DiskDrive
{
返回值类型 参数名称
uint16 Availability;
uint32 BytesPerSector;
uint16 Capabilities[];
string CapabilityDescriptions[];
string Caption;
string CompressionMethod;
uint32 ConfigManagerErrorCode;
boolean ConfigManagerUserConfig;
string CreationClassName;
uint64 DefaultBlockSize;
string Description;
string DeviceID;
boolean ErrorCleared;
string ErrorDescription;
string ErrorMethodology;
string FirmwareRevision;
uint32 Index;
datetime InstallDate;
string InterfaceType;
uint32 LastErrorCode;
string Manufacturer;
uint64 MaxBlockSize;
uint64 MaxMediaSize;
boolean MediaLoaded;
string MediaType;
uint64 MinBlockSize;
string Model;
string Name;
boolean NeedsCleaning;
uint32 NumberOfMediaSupported;
uint32 Partitions;
string PNPDeviceID;
uint16 PowerManagementCapabilities[];
boolean PowerManagementSupported;
uint32 SCSIBus;
uint16 SCSILogicalUnit;
uint16 SCSIPort;
uint16 SCSITargetId;
uint32 SectorsPerTrack;
string SerialNumber;
uint32 Signature;
uint64 Size;
string Status;
uint16 StatusInfo;
string SystemCreationClassName;
string SystemName;
uint64 TotalCylinders;
uint32 TotalHeads;
uint64 TotalSectors;
uint64 TotalTracks;
uint32 TracksPerCylinder;
};
获取网卡的MAC地址
MAC地址也叫物理地址、硬件地址,由网络设备制造商生产时烧录在网卡(Network lnterface Card)的EPROM(一种闪存芯片,通常可以通过程序擦写)。
获取正在使用的网卡的地址,不会获取全部的网卡地址
/// <summary>
/// 获取网卡硬件地址
/// </summary>
/// <returns></returns>
public static string GetMacAddress()
{
var mac = "";
var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
var moc = mc.GetInstances();
foreach (var o in moc)
{
var mo = (ManagementObject)o;
if (!(bool)mo["IPEnabled"]) continue;
mac = mo["MacAddress"].ToString();
break;
}
return mac;
}
获取BIOS
Win+R 输入cmd然后输入systeminfo ,可以查看BIOS信息
BIOS的更多操作
添加链接描述
使用方式是:替换foreach中的中括号中参数的名称,
/// <summary>
/// 获取BIOS信息,
/// </summary>
/// <returns></returns>
public static string GetBIOS()
{
string BIOSStr ="";
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("Select SerialNumber From Win32_BIOS");
ManagementObjectCollection moc = searcher.Get();
if (moc.Count > 0)
{
foreach (ManagementObject share in moc)
{
BIOSStr = share["SerialNumber"].ToString();
}
}
return BIOSStr;
}
Enjoy
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)