Search code examples
c#.netwmi

How do I check to see if a value exists in PropertyDataCollection?


I have a class which collects information from servers using WMI. The problem is that some versions of windows seem to have different properties available/missing and I cannot seem to find a way to check the collection to see if a value exists before I attempt to access their value.

To be clear, I have found it possible to loop through the entire collection and check each property name value by using wmiSingle.Properties.GetEnumerator() - but there must be a better way. Right?

ManagementScope wmiScope = new ManagementScope("\\\\MyLaptop\\root\\cimv2");
ObjectQuery wmiVolumeQuery = new System.Management.ObjectQuery("SELECT * FROM Win32_Processor");

using (ManagementObjectSearcher wmiObjectSearcher = new ManagementObjectSearcher(wmiScope, wmiVolumeQuery))
{
    using (ManagementObjectCollection wmiMany = wmiObjectSearcher.Get())
    {
        foreach (ManagementObject wmiSingle in wmiMany)
        {
            Console.WriteLine(wmiSingle["Name"]);

            //This line will throw an exception. How do I test to see if
            //  "SomeProperty" exists before attempting to access the value?
            //Console.WriteLine(wmiSingle["SomeProperty"]);
            object somePropertyValue = wmiSingle.GetPropertyValue("SomeProperty");
        }
    }
}

Solution

  • I believe the only way to check this is to iterate through the Properties

    foreach (var prop in wmiSingle.Properties)
    {
        if(prop.Name == "SomeProperty")
        { /* do something */ }        
    }
    

    You could also just catch the exception - like this

    public static class Extensions
    {
        public static object TryGetProperty(this System.Management.ManagementObject wmiObj, string propertyName)
        {
            object retval;
            try
            {
                retval = wmiObj.GetPropertyValue(propertyName);
            }
            catch (System.Management.ManagementException ex)
            {
                retval = null;
            }
            return retval;
        }
    }
    

    Intentionally / knowingly causing exceptions to be thrown is typically not efficient; however, neither is iterating through an entire collection looking for a single property.