中文字幕日韩精品一区二区免费_精品一区二区三区国产精品无卡在_国精品无码专区一区二区三区_国产αv三级中文在线

ManagementClass類解析和C#如何獲取硬件的相關(guān)信息-創(chuàng)新互聯(lián)

 在.NET的項(xiàng)目中,有時(shí)候需要獲取計(jì)算機(jī)的硬件的相關(guān)信息,在C#語言中需要利用ManagementClass這個(gè)類來進(jìn)行相關(guān)操作。

尖草坪ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場景,ssl證書未來市場廣闊!成為創(chuàng)新互聯(lián)建站的ssl證書銷售渠道,可以享受市場價(jià)格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18980820575(備注:SSL證書合作)期待與您的合作!

 現(xiàn)在先來介紹一下ManagementClass類,首先看一下類的繼承結(jié)構(gòu):

ManagementClass類解析和C#如何獲取硬件的相關(guān)信息

  現(xiàn)在看一下MSDN對(duì)ManagementClass類的解釋,對(duì)表示一個(gè)通用信息模型 (CIM) 管理類。 管理類是 WMI 類,如 Win32_LogicalDisk, ,該類型可表示一個(gè)磁盤驅(qū)動(dòng)器,并 Win32_Process, ,它表示的進(jìn)程 Notepad.exe 等。 此類的成員可以訪問 WMI 數(shù)據(jù),使用一個(gè)特定的 WMI 類路徑。

一. 接下來我們來看一下ManagementClass類中一些較為常用的方法的源碼:

1.GetInstances():此方法存在四個(gè)重載

ManagementClass類解析和C#如何獲取硬件的相關(guān)信息下面提供一下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():

ManagementClass類解析和C#如何獲取硬件的相關(guān)信息

下面提供一下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():此方法存在四個(gè)重載版本

ManagementClass類解析和C#如何獲取硬件的相關(guān)信息

下面提供一下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); 
         }

以上是對(duì)ManagementClass類的部分誰明,此類型的所有公共靜態(tài)成員都是線程安全的。不保證所有實(shí)例成員都是線程安全的。

二.ManagementClass類的部分應(yīng)用:

  /// <summary>
        /// 獲得CPU編號(hào)
        /// </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;
        }

        /// <summary>
        /// 獲取硬盤序列號(hào)
        /// </summary>
        /// <returns></returns>
        public string GetDiskSerialNumber()
        {
            //這種模式在插入一個(gè)U盤后可能會(huì)有不同的結(jié)果,如插入我的手機(jī)時(shí)
            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;
                //這名話解決有多個(gè)物理盤時(shí)產(chǎn)生的問題,只取第一個(gè)物理硬盤
                break;
            }
            return hDid;
        }

        /// <summary>
        /// 獲取網(wǎng)卡硬件地址
        /// </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;
        }

        /// <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;
        }

        /// <summary>
        /// 操作系統(tǒng)的登錄用戶名
        /// </summary>
        /// <returns></returns> 
        public string GetUserName()
        {
            return Environment.UserName;
        }


        /// <summary>
        /// 獲取計(jì)算機(jī)名
        /// </summary>
        /// <returns></returns>
        public string GetComputerName()
        {
            return Environment.MachineName;
        }

        /// <summary>
        /// 操作系統(tǒng)類型
        /// </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;
        }

        /// <summary>
        /// 物理內(nèi)存
        /// </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;
        }

        /// <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;
        }

        /// <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;
        }

        /// <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;
        }

        /// <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;
        }

        /// <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;
        }

        /// <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();
        }

        /// <summary>
        /// 主板編號(hào)
        /// </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;
        }

        /// <summary>
        /// 主板型號(hào)
        /// </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;
        }

創(chuàng)新互聯(lián)www.cdcxhl.cn,專業(yè)提供香港、美國云服務(wù)器,動(dòng)態(tài)BGP最優(yōu)骨干路由自動(dòng)選擇,持續(xù)穩(wěn)定高效的網(wǎng)絡(luò)助力業(yè)務(wù)部署。公司持有工信部辦法的idc、isp許可證, 機(jī)房獨(dú)有T級(jí)流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確進(jìn)行流量調(diào)度,確保服務(wù)器高可用性。佳節(jié)活動(dòng)現(xiàn)已開啟,新人活動(dòng)云服務(wù)器買多久送多久。

網(wǎng)站欄目:ManagementClass類解析和C#如何獲取硬件的相關(guān)信息-創(chuàng)新互聯(lián)
標(biāo)題鏈接:http://www.rwnh.cn/article44/cchpee.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供建站公司、網(wǎng)站設(shè)計(jì)公司、用戶體驗(yàn)、網(wǎng)站收錄、響應(yīng)式網(wǎng)站、定制開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)
泗阳县| 嘉善县| 东乌珠穆沁旗| 英吉沙县| 新兴县| 屏东县| 东辽县| 钟山县| 宝清县| 凤阳县| 余庆县| 嘉兴市| 怀安县| 吴堡县| 镇宁| 兴安县| 且末县| 肇东市| 阿拉善盟| 海伦市| 孟津县| 射洪县| 台中县| 湘西| 邢台县| 眉山市| 武平县| 富锦市| 海口市| 东城区| 宜兰县| 阿克陶县| 宁安市| 哈尔滨市| 腾冲县| 连平县| 全州县| 五常市| 镶黄旗| 临沭县| 嘉兴市|