BLOG.CSHARPHELPER.COM: Use WMI to get lots of information about the operating system in C#
Use WMI to get lots of information about the operating system in C#
When the program starts, it executes the query WMI "SELECT * FROM Win32_OperatingSystem." It loops through the results and calls subroutine GetValue for each of the many system parameters that should be available. The following code shows just a couple of the GetValue calls.
// Get and display OS properties. private void Form1_Load(object sender, EventArgs e) { ManagementObjectSearcher os_searcher = new ManagementObjectSearcher( "SELECT * FROM Win32_OperatingSystem"); foreach (ManagementObject mobj in os_searcher.Get()) { GetValue(mobj, "BootDevice"); GetValue(mobj, "BuildNumber"); GetValue(mobj, "BuildType"); GetValue(mobj, "Caption"); ... // Auto-size the columns. foreach (ColumnHeader col in lvwResults.Columns) { col.Width = -2; } }
The code first creates a ManagementObjectSearcher to execute the query. (To use this class, add a Reference to System.Management and add a using statement for System.Management.)
Next the code loops through the returned ManagementObjects (there should be only one) and calls the GetValue method to get a bunch of values from the ManagementObject.
The following code shows the GetValue method.
// Get a value from the ManagementObject. private void GetValue(ManagementObject mobj, string property_name) { string value; try { value = mobj[property_name].ToString(); } catch (Exception ex) { value = "*** Error: " + ex.Message; }
This method uses the property's name as a ManagementObject index. It converts the property into a string (if possible) and adds the name and its value to the program's ListView control.
This example fetches these properties:
Comments