Question

I know how to gain access to management-objects. Lets say this one:

var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter");            
foreach (var nic in searcher.Get())
{                
    Console.WriteLine(nic["caption"]);
}

Now this nic[]-synthax is very bad to use. If I take a look at visual studios server explorer I see, that it fills up a property grid for each object I select. Smells like they are creating bindable classes there. Are there any libs or approaches to do the same? I would like to get a syntax like

var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter");            
foreach (var nic in searcher.Get())
{                
    Console.WriteLine((nic as Win32NetworkAdapter).Caption);
}

I just don't want to waste my time implementing something new which was invented already!

Was it helpful?

Solution

WMI takes a query and returns an indeterminate set of results. The query is SQL-like, so it may return only certain columns. The properties grid simply enumerates each returned value into separate names and values. There's no fixed column set for any query result. For this reason, you'll need to explicitly fetch each one from the returned list.

OTHER TIPS

Why not use the Mgmtclassgen.exe (Management Strongly Typed Class Generator) which is part of Visual Studio?

Just to make others happy like me, I've created a T4 for solving my problem. It's documented at http://www.codingfreaks.de/2011/11/22/t4-fur-wmi-zugriff/ (in German!!!) and can be obtained at http://www.codingfreaks.de/files/wmi01/WmiHelper.tt. To make it work, just

  1. Add it to your Project in VS.
  2. Add a text-file named "Classes.txt".
  3. Add a line for each WMI-Class you want to use in "Classes.txt" (e.g. "Win32_NetworkAdapter")
  4. Right-click the tt-file in the project and use "user-defined tool".
  5. Go to your code and type WmiHelper.*

Enjoy!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top