Search code examples
c#wmi

How do I programmatically determine which WMI property is the primary key of a class?


I need to dynamically determine which property of a WMI class is the primary key in C#.

I can manually locate this information using CIM Studio or the WMI Delphi Code Creator but I need to find all property names of a class and flag which is / are the key / keys... and I already know how to find the property names of a class.

Manual identification of the key is covered in a related answer and I'm hoping the author (I'm looking at RRUZ) might be able to fill me in on how they locate the key (or anyone else who might know).

Many thanks.


Solution

  • To get the key field of a WMI class, you must iterate over the qualifiers of the properties for the WMI class and then search for the qualifier called key and finally check if the value of that qualifier is true.

    Try this sample

    using System;
    using System.Collections.Generic;
    using System.Management;
    using System.Text;
    
    namespace GetWMI_Info
    {
        class Program
        {
    
            static string GetKeyField(string WmiCLass)
            {
                string key = null; 
                ManagementClass manClass = new ManagementClass(WmiCLass);
                manClass.Options.UseAmendedQualifiers = true;
                foreach (PropertyData Property in manClass.Properties)
                    foreach (QualifierData Qualifier in Property.Qualifiers)
                        if (Qualifier.Name.Equals("key") && ((System.Boolean)Qualifier.Value))                        
                            return Property.Name;
                return key;                                                    
            }
    
            static void Main(string[] args)
            {
                try
                {
                    Console.WriteLine(String.Format("The Key field of the WMI class {0} is {1}", "Win32_DiskPartition", GetKeyField("Win32_DiskPartition")));
                    Console.WriteLine(String.Format("The Key field of the WMI class {0} is {1}", "Win32_Process", GetKeyField("Win32_Process")));
                }
                catch (Exception e)
                {
                    Console.WriteLine(String.Format("Exception {0} Trace {1}", e.Message, e.StackTrace));
                }
                Console.WriteLine("Press Enter to exit");
                Console.Read();
            }
        }
    }