How to retrieve hardware information using the ManagementClass class in C#?
To obtain hardware information using the ManagementClass class, first you need to reference the System.Management namespace. Then you can proceed with the following steps:
- Instantiate a ManagementObjectSearcher object for executing WMI queries. This object can be initialized by specifying the query statement and scope, such as “SELECT * FROM Win32_Processor” to retrieve processor information.
using System.Management;
// ...
string query = "SELECT * FROM Win32_Processor";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
- Call the Get() method to perform a query and store the results in a ManagementObjectCollection object.
ManagementObjectCollection collection = searcher.Get();
- Iterate through the ManagementObjectCollection object, printing out or saving the property values of each ManagementObject object.
foreach (ManagementObject obj in collection)
{
foreach (PropertyData property in obj.Properties)
{
Console.WriteLine(property.Name + ": " + property.Value);
}
}
The above code is just an example of how to retrieve processor information. If you want to obtain information on other hardware, you can replace “Win32_Processor” in the query statement with other WMI class names, such as “Win32_PhysicalMemory” for retrieving physical memory information.
When using the ManagementClass class to retrieve hardware information, it is necessary to add access permissions for administrative rights in the program. You can either check the “Request Management Permissions” option in the Manifest tab in project properties, or run the program as an administrator.