Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

WMI Proxy Class using System.Dynamic

4.50/5 (2 votes)
30 Aug 2012CPOL 15.4K   151  
A wrapper class to access WMI objects using dynamic variables

This article appears in the Third Party Products and Tools section. Articles in this section are for the members only and must not be used to promote or advertise products in any way, shape or form. Please report any spam or advertising.

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):
    C#
    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):
    C#
    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()));
                        }
                    }
                }
            }    

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)