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.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a comment

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.