Finding all network adapters using WMI in C# .NET

In this post we saw how to retrieve all logical drives using Windows Management Intrumentation (WMI). We’ll follow a very similar technique to enumerate all network adapters.

The following code prints all non-null properties of all network drives found on the local – “root” – computer:

private static void ListAllNetworkAdapters()
{
	ManagementObjectSearcher networkAdapterSearcher = new ManagementObjectSearcher("root\\cimv2", "select * from Win32_NetworkAdapterConfiguration");
	ManagementObjectCollection objectCollection = networkAdapterSearcher.Get();

	Console.WriteLine("There are {0} network adapaters: ", objectCollection.Count);

	foreach (ManagementObject networkAdapter in objectCollection)
	{
		PropertyDataCollection networkAdapterProperties = networkAdapter.Properties;
		foreach (PropertyData networkAdapterProperty in networkAdapterProperties)
		{
			if (networkAdapterProperty.Value != null)
			{
				Console.WriteLine("Network adapter property name: {0}", networkAdapterProperty.Name);
				Console.WriteLine("Network adapter property value: {0}", networkAdapterProperty.Value);
			}
		}
		Console.WriteLine("---------------------------------------");
	}
}

Here’s an extract of the printout from my PC:

Network adapters extract console view

You can view all posts related to Diagnostics here.

Advertisement

Finding all WMI class properties with .NET C#

In this post we saw how to enumerate all WMI – Windows Management Intrumentation – namespaces and classes. Then in this post we saw an example of querying the system to retrieve all local drives:

ObjectQuery objectQuery = new ObjectQuery("SELECT Size, Name FROM Win32_LogicalDisk where DriveType=3");

The properties that we’re after are like “Size” and “Name” of Win32_LogicalDisk. There’s a straightforward solution as we can select all properties in the object query. The following method will print all properties available in the WMI class, their types and values:

private static void PrintPropertiesOfWmiClass(string namespaceName, string wmiClassName)
{
	ManagementPath managementPath = new ManagementPath();
	managementPath.Path = namespaceName;
	ManagementScope managementScope = new ManagementScope(managementPath);
	ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM " + wmiClassName);
	ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher(managementScope, objectQuery);
	ManagementObjectCollection objectCollection = objectSearcher.Get();
	foreach (ManagementObject managementObject in objectCollection)
	{
		PropertyDataCollection props = managementObject.Properties;
		foreach (PropertyData prop in props)
		{
			Console.WriteLine("Property name: {0}", prop.Name);
			Console.WriteLine("Property type: {0}", prop.Type);
			Console.WriteLine("Property value: {0}", prop.Value);
		}
	}
}

You’ll need to run this with VS as an administrator. Also, there’s no authentication so we’ll use this code to investigate the class properties on the local machine. Otherwise see the posts referred to above for an example to read WMI objects from another machine on your network.

Let’s see what’s there for us in the cimv2/Win32_LocalTime class:

PrintPropertiesOfWmiClass("root\\cimv2", "Win32_LocalTime");

I got the following output:

WMI class property name reader

Let’s see another one:

PrintPropertiesOfWmiClass("root\\cimv2", "Win32_BIOS");

Some interesting property values from the BIOS properties of my PC:

BIOS WMI properties

You can view all posts related to Diagnostics here.

Finding all WMI class names within a WMI namespace with .NET C#

In this post we saw an example of using WMI objects such as ConnectionOptions, ObjectQuery and ManagementObjectSearcher to enumerate all local drives on a computer. Recall the SQL-like query we used:

ObjectQuery objectQuery = new ObjectQuery("SELECT Size, Name FROM Win32_LogicalDisk where DriveType=3");

We’ll now see a technique to list all WMI classes within a WMI namespace. First we get hold of the WMI namespaces:

private static List<String> GetWmiNamespaces(string root)
{
	List<String> namespaces = new List<string>();
	try
	{
		ManagementClass nsClass = new ManagementClass(new ManagementScope(root), new ManagementPath("__namespace"), null);
		foreach (ManagementObject ns in nsClass.GetInstances())
		{
			string namespaceName = root + "\\" + ns["Name"].ToString();
			namespaces.Add(namespaceName);
			namespaces.AddRange(GetWmiNamespaces(namespaceName));
		}
	}
	catch (ManagementException me)
	{
		Console.WriteLine(me.Message);
	}

	return namespaces.OrderBy(s => s).ToList();
}

We call this method as follows to list all WMI namespaces on the local computer:

List<String> namespaces = GetWmiNamespaces("root");

The following method will retrieve all classes from a WMI namespace using the ManagementObjectSearcher object and a query:

private static List<String> GetClassNamesWithinWmiNamespace(string wmiNamespaceName)
{
	List<String> classes = new List<string>();
	ManagementObjectSearcher searcher = new ManagementObjectSearcher
				(new ManagementScope(wmiNamespaceName),
				new WqlObjectQuery("SELECT * FROM meta_class"));
	List<string> classNames = new List<string>();
	ManagementObjectCollection objectCollection = searcher.Get();
	foreach (ManagementClass wmiClass in objectCollection)
	{
		string stringified = wmiClass.ToString();
		string[] parts = stringified.Split(new char[] { ':' });
		classes.Add(parts[1]);
	}
	return classes.OrderBy(s => s).ToList();
}

The ManagementClass ToString method attaches the class name to the namespace with a colon hence the Split method.

You can then call this method for each namespace name:

foreach (String namespaceName in namespaces)
{
	List<String> classNames = GetClassNamesWithinWmiNamespace(namespaceName);
}

Listing all class names within all namespaces can take a lot of time though.

You can view all posts related to Diagnostics here.

Finding all local drives using WMI in C# .NET

WMI – Windows Management Instrumentation – provides a set of tools to monitor the system resources, such as devices and applications. WMI is represented by the System.Management library that you set a reference to in a .NET project.

We’ll quickly look at how to enumerate all local drives on a computer in your network. You might need to run Visual Studio as an administrator:

ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.Username = "andras.nemes";
connectionOptions.Password = "p@ssw0rd";
			
ManagementPath managementPath = new ManagementPath();
managementPath.Path = "\\\\machinename\\root\\cimv2";

ManagementScope managementScope = new ManagementScope(managementPath, connectionOptions);

ObjectQuery objectQuery = new ObjectQuery("SELECT Size, Name FROM Win32_LogicalDisk where DriveType=3");

ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher(managementScope, objectQuery);
ManagementObjectCollection objectCollection = objectSearcher.Get();

foreach (ManagementObject managementObject in objectCollection)
{
	Console.WriteLine("Resource name: {0}", managementObject["Name"]);
	Console.WriteLine("Resource size: {0}", managementObject["Size"]);
}

First we set up the user information to access the other computer with the ConnectionOptions object. Then we declare the path to the WMI namespace where the resource exists. In this case it’s “root\\cimv2”.

Further down you’ll see how to list all WMI namespaces.

Next we build a ManagementScope object using the management path and connection options inputs. Then comes the interesting part: an SQL-like syntax to query the resource, in this case Win32_LogicalDisk. This page lists all selectable properties of Win32_LogicalDisk including the values for DriveType.

ManagementObjectSearcher is the vehicle to run the query on the declared scope. The Get() method of ManagementObjectSearcher enumerates all management objects that the query returned. The loop prints the properties that we extracted using the query.

Here’s how you can print the WMI namespaces of a root:

private static List<String> GetWmiNamespaces(string root)
{
	List<String> namespaces = new List<string>();
	try
	{
		ManagementClass nsClass = new ManagementClass(new ManagementScope(root), new ManagementPath("__namespace"), null);
		foreach (ManagementObject ns in nsClass.GetInstances())
		{
			string namespaceName = root + "\\" + ns["Name"].ToString();
			namespaces.Add(namespaceName);
			namespaces.AddRange(GetWmiNamespaces(namespaceName));
		}
	}
	catch (ManagementException me)
	{
		Console.WriteLine(me.Message);
	}

	return namespaces;
}

If you’d like to enumerate the WMI namespaces on your local PC then you can call this function like…

List<String> namespaces = GetWmiNamespaces("root");

You can view all posts related to Diagnostics here.

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: