ManagementClass类解析和C#如何获取硬件的相关信息

ManagementClass类解析和C#如何获取硬件的相关信息

发布于2018-01-04 15:33:30阅读 1.5K0

       在.NET的项目中,有时候需要获取计算机的硬件的相关信息,在C#语言中需要利用ManagementClass这个类来进行相关操作。

    现在先来介绍一下ManagementClass类,首先看一下类的继承结构:

    现在看一下MSDN对ManagementClass类的解释,对表示一个通用信息模型 (CIM) 管理类。 管理类是 WMI 类,如 Win32_LogicalDisk, ,该类型可表示一个磁盘驱动器,并 Win32_Process, ,它表示的进程 Notepad.exe 等。 此类的成员可以访问 WMI 数据,使用一个特定的 WMI 类路径。

  一. 接下来我们来看一下ManagementClass类中一些较为常用的方法的源码:

  1.GetInstances():此方法存在四个重载

 下面提供一下GetInstances(EnumerationOptions options)重载版本的代码:

public ManagementObjectCollection GetInstances(EnumerationOptions options) 
         { 
            if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length))
                 throw new InvalidOperationException(); 

            Initialize ( false );
            IEnumWbemClassObject enumWbem = null;
 
            EnumerationOptions o = (null == options) ? new EnumerationOptions() : (EnumerationOptions)options.Clone();
             o.EnsureLocatable = false; o.PrototypeOnly = false;
 
             SecurityHandler securityHandler    = null;
            int status                        = (int)ManagementStatus.NoError;

             try 
            {
                securityHandler = Scope.GetSecurityHandler(); 
                            status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices() ).CreateInstanceEnum_(ClassName, 
                                                            o.Flags,
                                                             o.GetContext(), 
                                                            ref enumWbem
                                                              );
             }
            finally 
             {
                if (securityHandler != null) 
                    securityHandler.Reset(); 
            }
 
             if (status < 0)
            {
                 if ((status & 0xfffff000) == 0x80041000)
                     ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); 
                else
                     Marshal.ThrowExceptionForHR(status); 
            } 

            return new ManagementObjectCollection(Scope, o, enumWbem); 
        }

复制

  2.Get():

 下面提供一下Get()重载版本的代码:

 public ManagementObjectCollection Get() 
        {
            Initialize (); 
            IEnumWbemClassObject ew = null; 
            SecurityHandler securityHandler = scope.GetSecurityHandler();
            EnumerationOptions enumOptions = (EnumerationOptions)options.Clone(); 

            int status = (int)ManagementStatus.NoError;

            try 
            {
                if ((query.GetType() == typeof(SelectQuery)) && 
                    (((SelectQuery)query).Condition == null) &&
                    (((SelectQuery)query).SelectedProperties == null) &&
                    (options.EnumerateDeep == true))
                { 
                    enumOptions.EnsureLocatable = false; enumOptions.PrototypeOnly = false; 

                    if (((SelectQuery)query).IsSchemaQuery == false) 
                    {
                        status = scope.GetSecuredIWbemServicesHandler( scope.GetIWbemServices()  ).CreateInstanceEnum_(
                            ((SelectQuery)query).ClassName,
                            enumOptions.Flags, 
                            enumOptions.GetContext(),
                            ref ew); 
                    } 
                    else
                    { 
                        status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices() ).CreateClassEnum_(((SelectQuery)query).ClassName,
                            enumOptions.Flags,
                            enumOptions.GetContext(),
                            ref ew ); 
                    }
                } 
                else
                {
                    enumOptions.EnumerateDeep = true;
                    status = scope.GetSecuredIWbemServicesHandler(scope.GetIWbemServices() ).ExecQuery_(
                        query.QueryLanguage,
                        query.QueryString, 
                        enumOptions.Flags,
                        enumOptions.GetContext(), 
                        ref ew ); 
                }
            } 
            catch (COMException e)
            {
                //
                ManagementException.ThrowWithExtendedInfo(e); 
            }
            finally 
            { 
                securityHandler.Reset();
            } 

            if ((status & 0xfffff000) == 0x80041000)
            {
                ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); 
            }
            else if ((status & 0x80000000) != 0) 
            { 
                Marshal.ThrowExceptionForHR(status);
            } 
            return new ManagementObjectCollection(scope, options, ew); 
        }

复制

3.GetSubclasses():此方法存在四个重载版本

 下面提供一下GetSubclasses(EnumerationOptions options)重载版本的代码:

public ManagementObjectCollection GetSubclasses(EnumerationOptions options)
        { 
             if (null == Path) 
                throw new InvalidOperationException();
 
             Initialize ( false ) ;
             IEnumWbemClassObject enumWbem = null;
            EnumerationOptions o = (null == options) ? new EnumerationOptions() : (EnumerationOptions)options.Clone(); 
            o.EnsureLocatable = false; o.PrototypeOnly = false; 
            SecurityHandler securityHandler = null; 
             int status                        = (int)ManagementStatus.NoError;

            try
             { 
                 securityHandler = Scope.GetSecurityHandler();
                            status = scope.GetSecuredIWbemServicesHandler( Scope.GetIWbemServices() ).CreateClassEnum_(ClassName, 
                    o.Flags, 
                     o.GetContext(),
                    ref enumWbem); 
            }
            finally
             {
                if (securityHandler != null) 
                     securityHandler.Reset();
             } 
 
            if (status < 0)
             { 
                if ((status & 0xfffff000) == 0x80041000)
                    ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
                else
                     Marshal.ThrowExceptionForHR(status); 
            }
 
             return new ManagementObjectCollection(Scope, o, enumWbem); 
         }

复制

  以上是对ManagementClass类的部分谁明,此类型的所有公共静态成员都是线程安全的。不保证所有实例成员都是线程安全的。

二.ManagementClass类的部分应用:

 1.获得CPU编号

        /// <summary>
        /// 获得CPU编号
        /// </summary>
        /// <returns></returns>
        public string GetCpuid()
        {
            var cpuid = string.Empty;
            var mc = new ManagementClass("Win32_Processor");
            var moc = mc.GetInstances();
            foreach (var o in moc)
            {
                var mo = (ManagementObject) o;
                cpuid = mo.Properties["ProcessorId"].Value.ToString();
            }
            return cpuid;
        }

复制

2.获取硬盘序列号

        /// <summary>
        /// 获取硬盘序列号
        /// </summary>
        /// <returns></returns>
        public 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 = (string)mo.Properties["Model"].Value;
                //这名话解决有多个物理盘时产生的问题,只取第一个物理硬盘
                break;
            }
            return hDid;
        }

复制

3.获取网卡硬件地址

        /// <summary>
        /// 获取网卡硬件地址
        /// </summary>
        /// <returns></returns> 
        public 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;
        }

复制

4.获取IP地址

        /// <summary>
        /// 获取IP地址
        /// </summary>
        /// <returns></returns>
        public string GetIpAddress()
        {
            var st = string.Empty;
            var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            var moc = mc.GetInstances();
            foreach (var o in moc)
            {
                var mo = (ManagementObject) o;
                if (!(bool) mo["IPEnabled"]) continue;
                var ar = (Array)(mo.Properties["IpAddress"].Value);
                st = ar.GetValue(0).ToString();
                break;
            }
            return st;
        }

复制

5.操作系统的登录用户名

        /// <summary>
        /// 操作系统的登录用户名
        /// </summary>
        /// <returns></returns> 
        public string GetUserName()
        {
            return Environment.UserName;
        }

复制

6.获取计算机名

        /// <summary>
        /// 获取计算机名
        /// </summary>
        /// <returns></returns>
        public string GetComputerName()
        {
            return Environment.MachineName;
        }

复制

7.操作系统类型

        /// <summary>
        /// 操作系统类型
        /// </summary>
        /// <returns></returns> 
        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;
        }

复制

8.物理内存

       /// <summary>
        /// 物理内存
        /// </summary>
        /// <returns></returns>
        public string GetPhysicalMemory()
        {
            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["TotalPhysicalMemory"].ToString();
            }
            return st;
        }

复制

9.显卡PNPDeviceID

       /// <summary>
        /// 显卡PNPDeviceID
        /// </summary>
        /// <returns></returns>
        public string GetVideoPnpid()
        {
            var st = "";
            var mos = new ManagementObjectSearcher("Select * from Win32_VideoController");
            foreach (var o in mos.Get())
            {
                var mo = (ManagementObject) o;
                st = mo["PNPDeviceID"].ToString();
            }
            return st;
        }

复制

10.声卡PNPDeviceID

       /// <summary>
        /// 声卡PNPDeviceID
        /// </summary>
        /// <returns></returns>
        public string GetSoundPnpid()
        {
            var st = string.Empty;
            var mos = new ManagementObjectSearcher("Select * from Win32_SoundDevice");
            foreach (var o in mos.Get())
            {
                var mo = (ManagementObject) o;
                st = mo["PNPDeviceID"].ToString();
            }
            return st;
        }

复制

11.CPU版本信息

        /// <summary>
        /// CPU版本信息
        /// </summary>
        /// <returns></returns>
        public string GetCpuVersion()
        {
            var st = string.Empty;
            var mos = new ManagementObjectSearcher("Select * from Win32_Processor");
            foreach (var o in mos.Get())
            {
                var mo = (ManagementObject) o;
                st = mo["Version"].ToString();
            }
            return st;
        }

复制

12.CPU名称信息

        /// <summary>
        /// CPU名称信息
        /// </summary>
        /// <returns></returns>
        public string GetCpuName()
        {
            var st = string.Empty;
            var driveId = new ManagementObjectSearcher("Select * from Win32_Processor");
            foreach (var o in driveId.Get())
            {
                var mo = (ManagementObject) o;
                st = mo["Name"].ToString();
            }
            return st;
        }

复制

13. CPU制造厂商

        /// <summary>
        /// CPU制造厂商
        /// </summary>
        /// <returns></returns>
        public string GetCpuManufacturer()
        {
            var st = string.Empty;
            var mos = new ManagementObjectSearcher("Select * from Win32_Processor");
            foreach (var o in mos.Get())
            {
                var mo = (ManagementObject) o;
                st = mo["Manufacturer"].ToString();
            }
            return st;
        }

复制

14.主板制造厂商

        /// <summary>
        /// 主板制造厂商
        /// </summary>
        /// <returns></returns>
        public string GetBoardManufacturer()
        {
            var query = new SelectQuery("Select * from Win32_BaseBoard");
            var mos = new ManagementObjectSearcher(query);
            var data = mos.Get().GetEnumerator();
            data.MoveNext();
            var board = data.Current;
            return board.GetPropertyValue("Manufacturer").ToString();
        }

复制

15.主板编号

        /// <summary>
        /// 主板编号
        /// </summary>
        /// <returns></returns>
        public string GetBoardId()
        {
            var st = string.Empty;
            var mos = new ManagementObjectSearcher("Select * from Win32_BaseBoard");
            foreach (var o in mos.Get())
            {
                var mo = (ManagementObject) o;
                st = mo["SerialNumber"].ToString();
            }
            return st;
        }

复制

16.主板型号

        /// <summary>
        /// 主板型号
        /// </summary>
        /// <returns></returns>
        public string GetBoardType()
        {
            var st = string.Empty;
            var mos = new ManagementObjectSearcher("Select * from Win32_BaseBoard");
            foreach (var o in mos.Get())
            {
                var mo = (ManagementObject) o;
                st = mo["Product"].ToString();
            }
            return st;
        }

复制

   以上的获取硬件信息的方法可以直接封装在一个类中,可以在项目中直接引用,这样可以加快项目的开发速度

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
获取U盘ID序列号 VS2005编译通过,源码源自CSDN。已经测试好用。 可以获得U盘名称,制造商ID号 版本号 U盘序列号及容量 Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Management; namespace UDiskTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button2_Click(object sender, EventArgs e) { DriveInfo[] s = DriveInfo.GetDrives(); foreach (DriveInfo drive in s) { if (drive.DriveType == DriveType.Removable) { pf.Text = drive.Name.ToString(); break; } } ManagementClass cimobject = new ManagementClass("Win32_DiskDrive"); ManagementObjectCollection moc = cimobject.GetInstances(); foreach (ManagementObject mo in moc) { if (mo.Properties["InterfaceType"].Value.ToString() == "USB") { try { //产品名称 Caption.Text = mo.Properties["Caption"].Value.ToString(); //总容量 Size.Text = mo.Properties["Size"].Value.ToString(); string[] info = mo.Properties["PNPDeviceID"].Value.ToString().Split('&'); string[] xx = info[3].Split('\\'); //序列号 MessageBox.Show("U盘序列号:" + xx[1]); PNPDeviceID.Text = xx[1]; xx = xx[0].Split('_'); //版本号 REV.Text = xx[1]; //制造商ID xx = info[1].Split('_'); VID.Text = xx[1]; } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } } } 如果编译遇到问题是using System.Management;无法找到引用找到, 项目(p)->添加引用(R)->找到.NET标签页 列表中下部位找到System.Management 双击点确定

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值