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>();
		ManagementClass nsClass = new ManagementClass(new ManagementScope(root), new ManagementPath("__namespace"), null);
		foreach (ManagementObject ns in nsClass.GetInstances())
			string namespaceName = root + "\\" + ns["Name"].ToString();
	catch (ManagementException me)

	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[] { ':' });
	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.

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

  1. Simple and well explained, thanks!!!

  2. hossein says:

    tnx very nice

Leave a Reply to Luis Bragagnolo Cancel reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

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

%d bloggers like this: