Introduction
I always wondered how diagnostic applications obtained the information about my system.
Background
I am writing an application which loads and uses JPG file for comparison and eventually for further treatment. The performance would suffer significantly if I had to load the files again and again, so I started to write a caching application for my JPG files. This application should use as much memory space as possible, without (if possible) forcing the system to use the virtual space on the harddisk. So my first task was to find out how much memory was installed in the current computer.
During my research, I located the necessary methods to obtain all kinds of information about installed hardware, motherboard, devices. Since I did not find the documentation easy to understand, I want to share my results now with the community.
Using the Code
It all starts with the 'ManagementClass
' which is using a system defined class name (e.g. "Win32_PhysicalMemory
"). This class name is used to create a management path of the requested data. The system contains a huge amount of class names, all listed here.
ManagementClass MgmtClass = new ManagementClass(new ManagementPath("Win32_PhysicalMemory"));
The information items in this class cannot be read out directly; we must create a collection of objects:
ManagementObjectCollection MOC = MgmtClass.GetInstances();
A management class may have multiple instances, e.g., when reading the information about the memory banks. The motherboard of my computer system is equipped with RAM in all four memory banks, so I will get four instances of the management class "Win32_PhysicalMemory
" and the same number of items in the management objects collection.
A complete list of all information objects of all memory management instances is now obtained with two nested enumerations. The outer enumeration covers the instances of the management class; the inner enumeration returns all information items with their internal names and values. While the outer enumeration must be done using an enumerator, we can do the inner enumeration with a foreach
loop:
ManagementObjectCollection.ManagementObjectEnumerator MOE = MOC.GetEnumerator();
while (MOE.MoveNext()) {
ManagementBaseObject mbo = MOE.Current;
PropertyDataCollection pdc = mbo.Properties;
foreach (PropertyData pd in pdc) {
object value = pd.Value;
if (value == null) continue;
}
}
That's it. The complete code of this hardware features enumeration can be found in the attached ZIP file which contains all VS2015 files to compile and run the code.
Note: The sources contain three extra blocks of code which I wrote to obtain more specialized computer information. These blocks have been commented out since they are not required for the demo application.
History
- 2016-10-25: Initial edition