C# WMI Object Queries .Net 1.x

OK so if you ever needed to use Windows Management Interface to retrieve some shday OS-type values like battery serial numbers or MAC Addresses then you’re in luck. I had to do this today, albeit for relatively rare battery info. Here’s a snippet:
StringBuilder sb = new StringBuilder();
try
{
ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");
ManagementObjectCollection queryCollection = query.Get();
PropertyDataCollection.PropertyDataEnumerator en;
foreach (ManagementObject mo in queryCollection)
{
en = mo.Properties.GetEnumerator();
while (en.MoveNext())
{
if ((en.Current.Value != null) && (en.Current.Name.Contains("Description") || en.Current.Name.Equals("ServiceName") || en.Current.Name.Equals("IPAddress") || (en.Current.Name.Equals("MACAddress")) ))
//if (en.Current.Value != null)
{
if (en.Current.Name == "IPAddress")
{
Array mystr = (Array)en.Current.Value;
sb.Append(en.Current.Name + " : " + Convert.ToString(mystr.GetValue(0).ToString()) + "\r\n");
}
else
{
sb.Append(en.Current.Name + " : " + Convert.ToString(en.Current.Value) + "\r\n");
}
}
}
break;
}
}
catch (Exception e)
{
sb.Append("Exception : " + e.Message + "\r\n");
}

In this example we are retrieving the MAC Address of the device, but we may just as well replace Win32_NetworkAdapterConfiguration with Win32_Battery and get all the battery stuff for a laptop for example. Even the battery DeviceID. This is useful if you need to engineer locking mechanism or securty type stuff, provided you do it properly.

Also note that this method of calling the ManagementObjectSearcher comes from .Net Framework 1.1.  You will need to add the reference to System.Management to use the snippet.

Comments are closed.