简体   繁体   中英

Check If Property Exists On Object C#

I am using a wmi call to get some info shown below

   var queryObj = new ObjectQuery("SELECT * FROM Win32_Processor");
            var vmSearcher = new ManagementObjectSearcher(queryObj);

        foreach (ManagementObject MO in vmSearcher.Get())
        {
            if (MO.GetType().GetProperty("AddressWidth") != null)
            {
                Value = MO["AddressWidth"].ToString();
            }

            //TRY TO FORCE TO NOT EXIST TO TEST..IS THIS THE WAY TO FORCE A 
            //PROPERTY OUT??
            MO["CurrentClockSpeed"] = null;

            if (MO.GetType().GetProperty("CurrentClockSpeed") != null)
            {
                Value2 = MO["CurrentClockSpeed"].ToString();
            }
         }

The problem is some machines have some properties and others have other properties

How do I check if a property exists or not on a machine? What I have isn't working

What I ultimately want is to simply print out properties of my choosing (like the on in the code sample) if they exist

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM