Introduction
The purpose of this tip is to provide an easy-to-use class to access the properties of a WMI object using dynamic C# variables.
Background
It's true that the ManagementObject
class is already an easy-to-use object, but sometimes the need to access the properties of an object through indices or methods can be annoying. A developer wants to produce code in a faster and versatileway.
Thanks to the System.Dynamic.DynamicObject
, a developer can access methods and properties without worrying about the real structure of the object.
So I created a simple wrapper class to access to the properties and methods of the WMI classes by calling them directly from the code without accessing explicitly using the ManagementObject
class.
Using the Code
There are two way to use the code:
- Using the result of a call to the
static
method Query
(comfortable):
private static void ListServices()
{
Console.WriteLine("Service list:");
foreach (dynamic item in WmiClass.Query("select * from Win32_Service"))
{
Console.WriteLine(" {0}, InterrogateService result={1}",
item.Name, ((InterrogateServiceResult)item.InterrogateService()));
}
}
- Creating an instance of the
WmiClass
wrapper using the constructor (faster with big results):
private static void FastListServices()
{
Console.WriteLine("Another service list:");
using (ManagementObjectSearcher searcher =
new ManagementObjectSearcher("select * from Win32_Service"))
{
foreach (ManagementObject obj in searcher.Get())
{
using (dynamic service = new WmiClass(obj))
{
Console.WriteLine(" {0}, InterrogateService result={1}",
service.Name, ((InterrogateServiceResult)service.InterrogateService()));
}
}
}
}