溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C#中ManagementObjectSearcher怎么用

發(fā)布時間:2021-08-30 09:36:39 來源:億速云 閱讀:1039 作者:小新 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細講解有關(guān)C#中ManagementObjectSearcher怎么用,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

在剛學(xué)C#,用ManagementObjectSearcher 竟然不能解析到頭文件,需要手動 Add Referance..

C#中ManagementObjectSearcher怎么用

前言: 

我們在很多情況下想要獲得計算機的硬件或操作系統(tǒng)的信息,比如獲得CPU序列號給自己的軟件添加機器碼鎖綁定指定電腦。又或者想要獲得硬盤分區(qū),聲卡顯卡等信息。

開篇:

我們用到的主要類是ManagementObjectSearcher,該類在System.Management命名空間下。 
有時候我們可以通過Environment獲得一些簡單的系統(tǒng)信息。 
如:Environment.MachineName;獲得計算機名。 
Environment.UserName;獲得操作系統(tǒng)登錄用戶名。 
不過在這篇文章中主要討論ManagementObjectSearcher獲取計算機硬件及操作系統(tǒng)的信息。

用法步驟:

  1. 添加引用:System.Management

  2. 引入命名空間:using System.Management;

  3. 創(chuàng)建ManagementObjectSearcher對象 
    anagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + Key); 
    其中的key見下面key列表:

  4. 通過searcher.Get()獲得ManagementObjectCollection集合

  5. 遍歷ManagementObjectCollection集合獲得ManagementObject

  6. 通過managementObject[name]或ManagementObject.GetPropertyValue(name)獲得想要的屬性 
    若不知道這里的name該寫什么可以遍歷打印一下:

foreach (var property in managementObject.Properties)
{
    Console.WriteLine(property.Name+":"+property.Value);
}

示例:

//獲取CPU序列號
public string GetCPUSerialNumber()
{
    try
    {
        ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Processor");
        string sCPUSerialNumber = "";
        foreach (ManagementObject mo in searcher.Get())
        {
            sCPUSerialNumber = mo["ProcessorId"].ToString().Trim();
            break;
        }
        return sCPUSerialNumber;
    }
    catch
    {
        return "";
    }
}
/獲取主板序列號
public string GetBIOSSerialNumber()
{
    try
    {
        ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_BIOS");
        string sBIOSSerialNumber = "";
        foreach (ManagementObject mo in searcher.Get())
        {
            sBIOSSerialNumber = mo.GetPropertyValue("SerialNumber").ToString().Trim();
            break;
        }
        return sBIOSSerialNumber;
    }
    catch
    {
        return "";
    }
}
//獲取硬盤序列號
public string GetHardDiskSerialNumber()
{
    try
    {
        ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
        string sHardDiskSerialNumber = "";
        foreach (ManagementObject mo in searcher.Get())
        {
            sHardDiskSerialNumber = mo["SerialNumber"].ToString().Trim();
            break;
        }
        return sHardDiskSerialNumber;
    }
    catch
    {
        return "";
    }
}
//獲取網(wǎng)卡地址
public string GetNetCardMACAddress()
{
    try
    {
        ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE ((MACAddress Is Not NULL) AND (Manufacturer <> 'Microsoft'))");
        string NetCardMACAddress = "";
        foreach (ManagementObject mo in searcher.Get())
        {
            NetCardMACAddress = mo["MACAddress"].ToString().Trim();
            break;
        }
        return NetCardMACAddress;
    }
    catch
    {
        return "";
    }
}

常用Key值:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + Key);
 
// 硬件 
Win32_Processor, // CPU 處理器 
Win32_PhysicalMemory, // 物理內(nèi)存條 
Win32_Keyboard, // 鍵盤 
Win32_PointingDevice, // 點輸入設(shè)備,包括鼠標。 
Win32_FloppyDrive, // 軟盤驅(qū)動器 
Win32_DiskDrive, // 硬盤驅(qū)動器 
Win32_CDROMDrive, // 光盤驅(qū)動器 
Win32_BaseBoard, // 主板 
Win32_BIOS, // BIOS 芯片 
Win32_ParallelPort, // 并口 
Win32_SerialPort, // 串口 
Win32_SerialPortConfiguration, // 串口配置 
Win32_SoundDevice, // 多媒體設(shè)置,一般指聲卡。 
Win32_SystemSlot, // 主板插槽 (ISA & PCI & AGP) 
Win32_USBController, // USB 控制器 
Win32_NetworkAdapter, // 網(wǎng)絡(luò)適配器 
Win32_NetworkAdapterConfiguration, // 網(wǎng)絡(luò)適配器設(shè)置 
Win32_Printer, // 打印機 
Win32_PrinterConfiguration, // 打印機設(shè)置 
Win32_PrintJob, // 打印機任務(wù) 
Win32_TCPIPPrinterPort, // 打印機端口 
Win32_POTSModem, // MODEM 
Win32_POTSModemToSerialPort, // MODEM 端口 
Win32_DesktopMonitor, // 顯示器 
Win32_DisplayConfiguration, // 顯卡 
Win32_DisplayControllerConfiguration, // 顯卡設(shè)置 
Win32_VideoController, // 顯卡細節(jié)。 
Win32_VideoSettings, // 顯卡支持的顯示模式。 
 
// 操作系統(tǒng) 
Win32_TimeZone, // 時區(qū) 
Win32_SystemDriver, // 驅(qū)動程序 
Win32_DiskPartition, // 磁盤分區(qū) 
Win32_LogicalDisk, // 邏輯磁盤 
Win32_LogicalDiskToPartition, // 邏輯磁盤所在分區(qū)及始末位置。 
Win32_LogicalMemoryConfiguration, // 邏輯內(nèi)存配置 
Win32_PageFile, // 系統(tǒng)頁文件信息 
Win32_PageFileSetting, // 頁文件設(shè)置 
Win32_BootConfiguration, // 系統(tǒng)啟動配置 
Win32_ComputerSystem, // 計算機信息簡要 
Win32_OperatingSystem, // 操作系統(tǒng)信息 
Win32_StartupCommand, // 系統(tǒng)自動啟動程序 
Win32_Service, // 系統(tǒng)安裝的服務(wù) 
Win32_Group, // 系統(tǒng)管理組 
Win32_GroupUser, // 系統(tǒng)組帳號 
Win32_UserAccount, // 用戶帳號 
Win32_Process, // 系統(tǒng)進程 
Win32_Thread, // 系統(tǒng)線程 
Win32_Share, // 共享 
Win32_NetworkClient, // 已安裝的網(wǎng)絡(luò)客戶端 
Win32_NetworkProtocol, // 已安裝的網(wǎng)絡(luò)協(xié)議

所有Key:

Win32_1394Controller
Win32_1394ControllerDevice
Win32_Account
Win32_AccountSID
Win32_ACE
Win32_ActionCheck
Win32_AllocatedResource
Win32_ApplicationCommandLine
Win32_ApplicationService
Win32_AssociatedBattery
Win32_AssociatedProcessorMemory
Win32_BaseBoard
Win32_BaseService
Win32_Battery
Win32_Binary
Win32_BindImageAction
Win32_BIOS
Win32_BootConfiguration
Win32_Bus
Win32_CacheMemory
Win32_CDROMDrive
Win32_CheckCheck
Win32_CIMLogicalDeviceCIMDataFile
Win32_ClassicCOMApplicationClasses
Win32_ClassicCOMClass
Win32_ClassicCOMClassSetting
Win32_ClassicCOMClassSettings
Win32_ClassInfoAction
Win32_ClientApplicationSetting
Win32_CodecFile
Win32_COMApplication
Win32_COMApplicationClasses
Win32_COMApplicationSettings
Win32_COMClass
Win32_ComClassAutoEmulator
Win32_ComClassEmulator
Win32_CommandLineAccess
Win32_ComponentCategory
Win32_ComputerSystem
Win32_ComputerSystemProcessor
Win32_ComputerSystemProduct
Win32_COMSetting
Win32_Condition
Win32_CreateFolderAction
Win32_CurrentProbe
Win32_DCOMApplication
Win32_DCOMApplicationAccessAllowedSetting
Win32_DCOMApplicationLaunchAllowedSetting
Win32_DCOMApplicationSetting
Win32_DependentService
Win32_Desktop
Win32_DesktopMonitor
Win32_DeviceBus
Win32_DeviceMemoryAddress
Win32_DeviceSettings
Win32_Directory
Win32_DirectorySpecification
Win32_DiskDrive
Win32_DiskDriveToDiskPartition
Win32_DiskPartition
Win32_DisplayConfiguration
Win32_DisplayControllerConfiguration
Win32_DMAChannel
Win32_DriverVXD
Win32_DuplicateFileAction
Win32_Environment
Win32_EnvironmentSpecification
Win32_ExtensionInfoAction
Win32_Fan
Win32_FileSpecification
Win32_FloppyController
Win32_FloppyDrive
Win32_FontInfoAction
Win32_Group
Win32_GroupUser
Win32_HeatPipe
Win32_IDEController
Win32_IDEControllerDevice
Win32_ImplementedCategory
Win32_InfraredDevice
Win32_IniFileSpecification
Win32_InstalledSoftwareElement
Win32_IRQResource
Win32_Keyboard
Win32_LaunchCondition
Win32_LoadOrderGroup
Win32_LoadOrderGroupServiceDependencies
Win32_LoadOrderGroupServiceMembers
Win32_LogicalDisk
Win32_LogicalDiskRootDirectory
Win32_LogicalDiskToPartition
Win32_LogicalFileAccess
Win32_LogicalFileAuditing
Win32_LogicalFileGroup
Win32_LogicalFileOwner
Win32_LogicalFileSecuritySetting
Win32_LogicalMemoryConfiguration
Win32_LogicalProgramGroup
Win32_LogicalProgramGroupDirectory
Win32_LogicalProgramGroupItem
Win32_LogicalProgramGroupItemDataFile
Win32_LogicalShareAccess
Win32_LogicalShareAuditing
Win32_LogicalShareSecuritySetting
Win32_ManagedSystemElementResource
Win32_MemoryArray
Win32_MemoryArrayLocation
Win32_MemoryDevice
Win32_MemoryDeviceArray
Win32_MemoryDeviceLocation
Win32_MethodParameterClass
Win32_MIMEInfoAction
Win32_MotherboardDevice
Win32_MoveFileAction
Win32_MSIResource
Win32_networkAdapter
Win32_networkAdapterConfiguration
Win32_networkAdapterSetting
Win32_networkClient
Win32_networkConnection
Win32_networkLoginProfile
Win32_networkProtocol
Win32_NTEventlogFile
Win32_NTLogEvent
Win32_NTLogEventComputer
Win32_NTLogEventLog
Win32_NTLogEventUser
Win32_ODBCAttribute
Win32_ODBCDataSourceAttribute
Win32_ODBCDataSourceSpecification
Win32_ODBCDriverAttribute
Win32_ODBCDriverSoftwareElement
Win32_ODBCDriverSpecification
Win32_ODBCSourceAttribute
Win32_ODBCTranslatorSpecification
Win32_OnBoardDevice
Win32_OperatingSystem
Win32_OperatingSystemQFE
Win32_OSRecoveryConfiguration
Win32_PageFile
Win32_PageFileElementSetting
Win32_PageFileSetting
Win32_PageFileUsage
Win32_ParallelPort
Win32_Patch
Win32_PatchFile
Win32_PatchPackage
Win32_PCMCIAController
Win32_Perf
Win32_PerfRawData
Win32_PerfRawData_ASP_ActiveServerPages
Win32_PerfRawData_ASPnet_114322_ASPnetAppsv114322
Win32_PerfRawData_ASPnet_114322_ASPnetv114322
Win32_PerfRawData_ASPnet_ASPnet
Win32_PerfRawData_ASPnet_ASPnetApplications
Win32_PerfRawData_IAS_IASAccountingClients
Win32_PerfRawData_IAS_IASAccountingServer
Win32_PerfRawData_IAS_IASAuthenticationClients
Win32_PerfRawData_IAS_IASAuthenticationServer
Win32_PerfRawData_InetInfo_InternetInformationServicesGlobal
Win32_PerfRawData_MSDTC_DistributedTransactionCoordinator
Win32_PerfRawData_MSFTPSVC_FTPService
Win32_PerfRawData_MSSQLSERVER_SQLServerAccessMethods
Win32_PerfRawData_MSSQLSERVER_SQLServerBackupDevice
Win32_PerfRawData_MSSQLSERVER_SQLServerBufferManager
Win32_PerfRawData_MSSQLSERVER_SQLServerBufferPartition
Win32_PerfRawData_MSSQLSERVER_SQLServerCacheManager
Win32_PerfRawData_MSSQLSERVER_SQLServerDatabases
Win32_PerfRawData_MSSQLSERVER_SQLServerGeneralStatistics
Win32_PerfRawData_MSSQLSERVER_SQLServerLatches
Win32_PerfRawData_MSSQLSERVER_SQLServerLocks
Win32_PerfRawData_MSSQLSERVER_SQLServerMemoryManager
Win32_PerfRawData_MSSQLSERVER_SQLServerReplicationAgents
Win32_PerfRawData_MSSQLSERVER_SQLServerReplicationDist
Win32_PerfRawData_MSSQLSERVER_SQLServerReplicationLogreader
Win32_PerfRawData_MSSQLSERVER_SQLServerReplicationMerge
Win32_PerfRawData_MSSQLSERVER_SQLServerReplicationSnapshot
Win32_PerfRawData_MSSQLSERVER_SQLServerSQLStatistics
Win32_PerfRawData_MSSQLSERVER_SQLServerUserSettable
Win32_PerfRawData_netFramework_netCLRExceptions
Win32_PerfRawData_netFramework_netCLRInterop
Win32_PerfRawData_netFramework_netCLRJit
Win32_PerfRawData_netFramework_netCLRLoading
Win32_PerfRawData_netFramework_netCLRLocksAndThreads
Win32_PerfRawData_netFramework_netCLRMemory
Win32_PerfRawData_netFramework_netCLRRemoting
Win32_PerfRawData_netFramework_netCLRSecurity
Win32_PerfRawData_Outlook_Outlook
Win32_PerfRawData_PerfDisk_PhysicalDisk
Win32_PerfRawData_Perfnet_Browser
Win32_PerfRawData_Perfnet_Redirector
Win32_PerfRawData_Perfnet_Server
Win32_PerfRawData_Perfnet_ServerWorkQueues
Win32_PerfRawData_PerfOS_Cache
Win32_PerfRawData_PerfOS_Memory
Win32_PerfRawData_PerfOS_Objects
Win32_PerfRawData_PerfOS_PagingFile
Win32_PerfRawData_PerfOS_Processor
Win32_PerfRawData_PerfOS_System
Win32_PerfRawData_PerfProc_FullImage_Costly
Win32_PerfRawData_PerfProc_Image_Costly
Win32_PerfRawData_PerfProc_JobObject
Win32_PerfRawData_PerfProc_JobObjectDetails
Win32_PerfRawData_PerfProc_Process
Win32_PerfRawData_PerfProc_ProcessAddressSpace_Costly
Win32_PerfRawData_PerfProc_Thread
Win32_PerfRawData_PerfProc_ThreadDetails_Costly
Win32_PerfRawData_RemoteAccess_RASPort
Win32_PerfRawData_RemoteAccess_RASTotal
Win32_PerfRawData_RSVP_ACSPerRSVPService
Win32_PerfRawData_Spooler_PrintQueue
Win32_PerfRawData_TapiSrv_Telephony
Win32_PerfRawData_Tcpip_ICMP
Win32_PerfRawData_Tcpip_IP
Win32_PerfRawData_Tcpip_NBTConnection
Win32_PerfRawData_Tcpip_networkInterface
Win32_PerfRawData_Tcpip_TCP
Win32_PerfRawData_Tcpip_UDP
Win32_PerfRawData_W3SVC_WebService
Win32_PhysicalMedia
Win32_PhysicalMemory
Win32_PhysicalMemoryArray
Win32_PhysicalMemoryLocation
Win32_PNPAllocatedResource
Win32_PnPDevice
Win32_PnPEntity
Win32_PointingDevice
Win32_PortableBattery
Win32_PortConnector
Win32_PortResource
Win32_POTSModem
Win32_POTSModemToSerialPort
Win32_PowerManagementEvent
Win32_Printer
Win32_PrinterConfiguration
Win32_PrinterController
Win32_PrinterDriverDll
Win32_PrinterSetting
Win32_PrinterShare
Win32_PrintJob
Win32_PrivilegesStatus
Win32_Process
Win32_Processor
Win32_ProcessStartup
Win32_Product
Win32_ProductCheck
Win32_ProductResource
Win32_ProductSoftwareFeatures
Win32_ProgIDSpecification
Win32_ProgramGroup
Win32_ProgramGroupContents
Win32_ProgramGroupOrItem
Win32_Property
Win32_ProtocolBinding
Win32_PublishComponentAction
Win32_QuickFixEngineering
Win32_Refrigeration
Win32_Registry
Win32_RegistryAction
Win32_RemoveFileAction
Win32_RemoveIniAction
Win32_ReserveCost
Win32_ScheduledJob
Win32_SCSIController
Win32_SCSIControllerDevice
Win32_SecurityDescriptor
Win32_SecuritySetting
Win32_SecuritySettingAccess
Win32_SecuritySettingAuditing
Win32_SecuritySettingGroup
Win32_SecuritySettingOfLogicalFile
Win32_SecuritySettingOfLogicalShare
Win32_SecuritySettingOfObject
Win32_SecuritySettingOwner
Win32_SelfRegModuleAction
Win32_SerialPort
Win32_SerialPortConfiguration
Win32_SerialPortSetting
Win32_Service
Win32_ServiceControl
Win32_ServiceSpecification
Win32_ServiceSpecificationService
Win32_SettingCheck
Win32_Share
Win32_ShareToDirectory
Win32_ShortcutAction
Win32_ShortcutFile
Win32_ShortcutSAP
Win32_SID
Win32_SMBIOSMemory
Win32_SoftwareElement
Win32_SoftwareElementAction
Win32_SoftwareElementCheck
Win32_SoftwareElementCondition
Win32_SoftwareElementResource
Win32_SoftwareFeature
Win32_SoftwareFeatureAction
Win32_SoftwareFeatureCheck
Win32_SoftwareFeatureParent
Win32_SoftwareFeatureSoftwareElements
Win32_SoundDevice
Win32_StartupCommand
Win32_SubDirectory
Win32_SystemAccount
Win32_SystemBIOS
Win32_SystemBootConfiguration
Win32_SystemDesktop
Win32_SystemDevices
Win32_SystemDriver
Win32_SystemDriverPNPEntity
Win32_SystemEnclosure
Win32_SystemLoadOrderGroups
Win32_SystemLogicalMemoryConfiguration
Win32_SystemMemoryResource
Win32_SystemnetworkConnections
Win32_SystemOperatingSystem
Win32_SystemPartitions
Win32_SystemProcesses
Win32_SystemProgramGroups
Win32_SystemResources
Win32_SystemServices
Win32_SystemSetting
Win32_SystemSlot
Win32_SystemSystemDriver
Win32_SystemTimeZone
Win32_SystemUsers
Win32_TapeDrive
Win32_TemperatureProbe
Win32_Thread
Win32_TimeZone
Win32_Trustee
Win32_TypeLibraryAction
Win32_UninterruptiblePowerSupply
Win32_USBController
Win32_USBControllerDevice
Win32_UserAccount
Win32_UserDesktop
Win32_VideoConfiguration
Win32_VideoController
Win32_VideoSettings
Win32_VoltageProbe
Win32_WMIElementSetting
Win32_WMISetting

關(guān)于“C#中ManagementObjectSearcher怎么用”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI