Use WMI to get the operating system's name including its edition, plus some other information in C#
WMI (Windows Management Instrumentation) lets you use SQL-like statements to ask the computer about itself. This example uses it to get:
- The operating system name including its edition (Home, Ultimate, etc.), version, and Service Pack number
- The number of logical processors
- The number of bits the system uses (32 or 64)
The code uses the WMI query "SELECT * FROM Win32_OperatingSystem" to get information about the operating system. The result is a collection holding one Win32_OperatingSystem object. The code uses a loop to get that object and reads its properties. The Caption property gives the full operating system name including trademark symbols and the edition. Version returns the operating system's version. The ServicePackMajorVersion and ServicePackMinorVersion properties give the service pack information. Next the program executes the query "SELECT * FROM Win32_ComputerSystem" in a similar fashion to get the number of logical processors. It finishes by executing the query "SELECT * FROM Win32_Processor" to determine whether this is a 32-bit or 64-bit operating system.
// Display the operating system's name.
private void Form1_Load(object sender, EventArgs e)
{
// Get the OS information.
// For more information from this query, see:
// msdn.microsoft.com/library/aa394239.aspx
string os_query = "SELECT * FROM Win32_OperatingSystem";
ManagementObjectSearcher os_searcher =
new ManagementObjectSearcher(os_query);
foreach (ManagementObject info in os_searcher.Get())
{
lblCaption.Text = info.Properties["Caption"].Value.ToString().Trim();
lblVersion.Text = "Version " +
info.Properties["Version"].Value.ToString() +
" SP " +
info.Properties["ServicePackMajorVersion"].Value.ToString() + "." +
info.Properties["ServicePackMinorVersion"].Value.ToString();
}
// Get number of processors.
// For more information from this query, see:
// msdn.microsoft.com/library/aa394373.aspx
string cpus_query = "SELECT * FROM Win32_ComputerSystem";
ManagementObjectSearcher cpus_searcher =
new ManagementObjectSearcher(cpus_query);
foreach (ManagementObject info in cpus_searcher.Get())
{
lblCpus.Text = info.Properties["NumberOfLogicalProcessors"].Value.ToString()
+ " processors";
}
// Get 32- versus 64-bit.
// For more information from this query, see:
// msdn.microsoft.com/library/aa394373.aspx
string proc_query = "SELECT * FROM Win32_Processor";
ManagementObjectSearcher proc_searcher =
new ManagementObjectSearcher(proc_query);
foreach (ManagementObject info in proc_searcher.Get())
{
lblBits.Text = info.Properties["AddressWidth"].Value.ToString() + "-bit";
}
}


Comments