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

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

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

Manual key identification is covered in the linked answer , and I hope that the author (I look at RRUZ) could fill me in on how they determine the key (or anyone else who might know).

Thank you very much.

+4
source share
2 answers

To get the key field of the WMI class, you have to go through the qualifiers properties for the WMI class and then look for a qualifier called key and finally check if the value of this qualifier matches 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(); } } } 
+6
source

For those who wish, I expanded the answer RRUZ:

  • resolving the request to the remote machine and
  • Adding support for classes with several primary keys (as is the case with Win32_DeviceBus ).

     static void Main(string[] args) { foreach (var key in GetPrimaryKeys(@"root\cimv2\win32_devicebus")) { Console.WriteLine(key); } } static List<string> GetPrimaryKeys(string classPath, string computer = ".") { var keys = new List<string>(); var scope = new ManagementScope(string.Format(@"\\{0}\{1}", computer, System.IO.Path.GetDirectoryName(classPath))); var path = new ManagementPath(System.IO.Path.GetFileName(classPath)); var options = new ObjectGetOptions(null, TimeSpan.MaxValue, true); using (var mc = new ManagementClass(scope, path, options)) { foreach (var property in mc.Properties) { foreach (var qualifier in property.Qualifiers) { if (qualifier.Name.Equals("key") && ((System.Boolean)qualifier.Value)) { keys.Add(property.Name); break; } } } } return keys; } 
+2
source

Source: https://habr.com/ru/post/1486595/


All Articles